您的位置:首页 > 其它

实战给AW_Blog插件添加缓存(续)

2013-10-27 23:07 155 查看
两年前的文章(实战给AW_Blog插件添加缓存)描述了一个Block Cache的实例,最近发现代码其实写的有点累赘,后台保存时自动触发刷新缓存并不需要自己去写刷新的动作,系统原生的Model继承类Mage_Core_Model_Abstract里已经有实现这个动作的代码,只需要简单的配置下变量就能实现。修改后的方案如下(Block类的所需修改代码不变)

打开AW_Blog_Model_Post这个文件,在头部定义一个常量,再定义一个变量

const CACHE_TAG       = 'aw_blog';
protected $_cacheTag         = 'aw_blog';


结束,就这么简单,打开Mage_Core_Model_Abstract文件来看下为什么

protected function _afterSave()
{
$this->cleanModelCache();
Mage::dispatchEvent('model_save_after', array('object'=>$this));
Mage::dispatchEvent($this->_eventPrefix.'_save_after', $this->_getEventData());
return $this;
}


public function cleanModelCache()
{
$tags = $this->getCacheTags();

if ($tags !== false) {
Mage::app()->cleanCache($tags);
}
return $this;
}


public function getCacheTags()
{
$tags = false;
if ($this->_cacheTag) {
if ($this->_cacheTag === true) {
$tags = array();
} else {
if (is_array($this->_cacheTag)) {
$tags = $this->_cacheTag;
} else {
$tags = array($this->_cacheTag);
}
$idTags = $this->getCacheIdTags();
if ($idTags) {
$tags = array_merge($tags, $idTags);
}
}
}
return $tags;
}


从上往下依次看,当Model对象保存完毕时会触发cleanModelCache,cleanModelCache里去根据getCacheTags返回的值去定向刷新tags针对的cache,这样,之前定义的变量$_cacheTag的值所对应的cache就被成功刷新了。如果代码看的不是很明白的话,可以把getCacheTags的返回值输出来看下

2013-10-27T14:02:59+00:00 DEBUG (7): Array

(

[0] => aw_blog

[1] => aw_blog_2

)

数组里的两个元素就是刷新缓存时所指定的cache tag
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: