2015-01-08 53 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