2015-01-08 49 views
0

我想为cakephp 2.5.3实现一个高速缓存功能,与find查询相关,但是我想使所有与表相关的事件(update,delete,...)无效。 我把它编入AppModel.php,你能告诉我你对代码逻辑和效率有什么看法吗? 谢谢。CakePHP查询的高速缓存

public function find($conditions = null, $fields = array(), $order = null, $recursive = null) { 
    $keyName = sha1(serialize(func_get_args())); 
    if (Cache::read($this->table . '_' . $keyName, '5m') !== false) { 
     $this->log('read cache ' . $this->table . '_' . $keyName); 

     return Cache::read($this->table . '_' . $keyName, '5m'); 
    } else { 

     $data = parent::find($conditions, $fields, $order, $recursive); 
     Cache::write($this->table . '_' . $keyName, $data, '5m'); 
     $this->addToCacheList($keyName); 
     $this->log('add ' . $this->table . '_' . $keyName); 

     return $data; 
    } 
} 

public function afterSave($created, $options = array()) { 

    $this->flushCacheList(); 

    parent::afterSave($created, $options); 
} 

public function afterDelete() { 

    $this->flushCacheList(); 

    parent::afterDelete(); 
} 

public function addToCacheList($keyName) { 
    if (Cache::read($this->table, '5m') !== false) { 
     $values = Cache::read($this->table, '5m'); 
     $values[] = $keyName; 
    } else { 
     $values = array($keyName); 
    } 

    Cache::write($this->table, $values, '5m'); 
} 

public function flushCacheList() { 
    if (Cache::read($this->table, '5m')) { 
     $values = Cache::read($this->table, '5m'); 
     foreach($values AS $value) { 
      Cache::delete($this->table . '_' . $value, '5m'); 
      $this->log('flush ' . $this->table . '_' . $value); 
     } 
     Cache::delete($this->table, '5m'); 
    } 
} 
+0

zeflex,什么错误?你能解释错误吗? – Supravat

回答

0

CakePHP有已经a built in query cache

您如何看待代码逻辑和效率?

我不确定,但我认为你经常刷新缓存以提高效率。

不要去考虑性能基准它。唯一可靠的方法是基准。

,但是我要说cache the results of queries instead.

+0

我看到http://book.cakephp.org/2.0/en/core-libraries/caching.html#using-cache-to-store-common-query-results,但是在那里,您并未使更新/保存/删除操作。这就是为什么我实施这个,因为我没有找到类似的东西。当你说我经常冲洗缓存时,我会告诉是和否。我希望在任何表格上进行任何操作后都可以获得最新的结果。 – zeflex