我尝试在ZF1中实现缓存失效。我的想法是为缓存类添加一个监听器,这将在'invalidate'事件的情况下触发失效。
根据我在手册中学到的,正确的方法是将事件管理器添加到可能触发缓存失效的每个类,然后将缓存类监听器附加到它。但是做这么简单的任务似乎是一项非常艰巨的工作。
可以编写它以使其工作......喜欢: *任何类都可以触发'invalidate'事件 *每当触发invalidate事件时,都会调用CacheManager类的指定回调并清除缓存
答案 0 :(得分: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);
}
}