2013-04-18 52 views
1

我嘗試在ZF1中實現緩存失效。我的想法是添加一個偵聽器緩存類,這將觸發無效事件的'無效'的情況下。使用Zend Framework事件管理器清除緩存

從我在手冊中學到的正確方法是將事件管理器添加到可能觸發緩存失效的每個類,然後將緩存類偵聽器附加到它。但是做這麼簡單的工作似乎是一項可怕的工作。

可以編寫它,使其工作。像: *任何類可以觸發「無效」事件 *每當無效事件引發了的CacheManager類指定的回調被調用,並清除緩存

+0

ZF1有一個事件管理器嗎? –

+0

是的,自從1.12我猜(http://framework.zend.com/manual/1.12/en/zend.event-manager.event-manager.html) –

回答

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); 
    } 

} 
+0

在你的情況@Tomáš你可以使你的主要無效緩存摘要 –

+0

很酷,謝謝! –