フロントでキャッシュするプラグイン

※フロントコントローラーのdispatchでdispatchループをbreakできるコードを入れておく必要があります。*1

<?php
class CachePlugin extends Zend_Controller_Plugin_Abstract
{
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        $id = md5(serialize($request));
        if ($data = $this->getCache()->load($id)) {

            $this->_isCacheHit = true;
            $response = unserialize($data);

            Zend_Controller_Front::getInstance()->setResponse($response);

            $request->cancelDispatch(true);
            //$request->setDispatched(false);
        }
    }

    public function dispatchLoopShutdown()
    {
        if (! $this->_isCacheHit
            && ! $this->getResponse()->isRedirect()
            && ! $this->getResponse()->isException()) {

            $data = serialize($this->getResponse());

            $this->getCache()->save($data);

        }
    }

    public function isCacheHit()
    {
        return $this->_isCacheHit ? true : false;
    }
    public function getCache()
    {
        if (!isset($this->_cache)) {
            $this->_cache = Zend_Cache::factory($this->_frontendName,
                                                $this->_backendName,
                                                $this->_frontendOption,
                                                $this->_backendOption);
        }
        return $this->_cache;
    }

    public function __construct($frontendName = null,
                                $backendName = null,
                                $frontendOption = null,
                                $backendOption = null) {
        if (null !== $frontendName) {
            $this->_fronendName = $frontendName;
        }
        if (null !== $backendName) {
            $this->_backendName = $backendName;
        }
        if (null !== $frontendOption) {
            $this->_fronendOption = $frontendOption;
        }
        if (null !== $backendOption) {
            $this->_backendOption = $backendOption;
        }
    }
    protected function setCache(Zend_Cache $cache)
    {
        $this->_cache = $cache;
    }

    protected $_cache;

    protected $_isCacheHit = false;

    protected $_frontendName = 'Core';

    protected $_backendName = 'File';

    protected $_frontendOption = array();

    protected $_backendOption = array('cache_dir' => FL_PATH_CACHE);
}

*1:ところで、コーディングっていうと、最近だとHTMLソースを作る人なの?プログラミングのことをコーディングって言ったらおかしいのかな。