實戰給AW_Blog插件添加緩存(續)
兩年前的文章(實戰給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
最後更新:2017-04-03 14:53:55