1

我尝试在 ZF1 中实现缓存失效。我的想法是向缓存类添加一个侦听器,这将在发生“无效”事件时触发无效。

根据我在手册中学到的正确方法是将事件管理器添加到每个可能触发缓存失效的类,然后将缓存类侦听器附加到它。但是做这么简单的任务似乎需要做很多工作。

可以编写它以便它工作。比如:*任何类都可以触发'invalidate'事件*每当触发invalidate事件时,调用CacheManager类的指定回调并清除缓存

4

1 回答 1

0

我做了什么,希望它会有所帮助:

class Application_Service_Client extends Application_Service_AbstractService
{

    protected $cacheFormId = 'clientList';
    protected $index = 'client';

    public function __construct()
    {
        parent::__construct(new Application_Model_DbTable_Client());

        $this->events->attach('insert', function ($e) {
            $event  = $e->getName();
            $target = get_class($e->getTarget());

            $this->cleanCache('clientList');
        });
    }

    public function ajouterClient($data)
    {
        unset($data['csrfhash']);
        $id = $this->model->ajouter($data);
        $client = $this->findClient($id);

        $this->events()->trigger('insert', $this, $client);
        return $client;
    }

    public function formList()
    {
        mb_internal_encoding("UTF-8");

        $cache   = $this->getCache();
        $cacheId = $this->cacheFormId;

        if (!($toCache = $cache->load($cacheId))) {
            $itemAll = $this->findAll();
            foreach ($itemAll as $item) {
                $key[]  = $item['IDCLIENT'];
                $value[] = $item['NOM'] . ' ' . $item['PRENOM'];
            }

            $toCache = array_combine($key, $value);
            $cache->save($toCache, $cacheId);
        }

        return $toCache;
    }

}

和抽象类:

abstract class Application_Service_AbstractService
{
    protected $model;

    protected $cache;

    protected $events;

    public function __construct($model = null)
    {
        if (!is_null($model)) {
            $this->setModel($model);
        }

        $this->events();
        $this->setCache();
    }

    public function events(Zend_EventManager_EventCollection $events = null)
    {
        if (null !== $events) {
            $this->events = $events;
        } elseif (null === $this->events) {
            $this->events = new Zend_EventManager_EventManager(__CLASS__);
        }
        return $this->events;
    }

    public function setCache($cacheName = 'form')
    {
        $bootstrap = \Zend_Controller_Front::getInstance()->getParam('bootstrap');

        $cacheManager = $bootstrap->getResource('cachemanager');

        $this->cache = $cacheManager->getCache($cacheName);
    }

    /** 
     * Get a cache object from the cache manager 
     * 
     * @return Zend_Cache 
     */
    protected function getCache()  
    {
        if (!$this->cache) {
            $this->setCache();
        }
        return $this->cache;
    }

    protected function cleanCache($cacheId)
    {
        $this->cache->remove($cacheId);
    }

}
于 2014-01-22T15:56:48.843 回答