2012-06-23 111 views
6

我使用學說2的結果高速緩存的查詢檢索用戶的新郵件(短信應用)的數量:學說2結果緩存失效

$query->useResultCache(true, 500, 'messaging.nb_new_messages.'.$userId); 

我試圖否定這一高速緩存這樣(在我的實體庫中):

public function clearNbNewMessagesOfUserCache($userId) { 
    $cacheDriver = $this->getEntityManager()->getConfiguration()->getResultCacheImpl(); 
    $result = $cacheDriver->delete('skepin_messaging.nbNewMessages.'.$userId); 

    if (!$result) { 
     return false; 
    } 

    return $cacheDriver->flushAll(); 
} 

因此,我不需要在我的網站的每個頁面上進行無用的查詢。

我的問題:是一個推薦的做法?我最終會遇到問題嗎?

回答

2

我有想法建立一個onFlush掛鉤。 你有所有的實體排隊插入,更新和刪除,因此你可以根據實體名稱和標識符等無效的緩存

不幸的是,我還沒有建立任何事件偵聽器,但我絕對打算建立這樣的事情爲我的項目。

Here是教義文檔的鏈接爲onFlush事件

編輯: 甚至有一個實施的事件更簡單的方法。 在實體類中,您可以將@HasLifecycleCallbacks添加到註釋中,並且可以使用@PreUpdate或@PrePersist註釋定義函數。 比每次更新或持續此模型時,都會調用此函數。

/** 
* @Entity 
* @Table(name="SomeEntity") 
* @HasLifecycleCallbacks 
*/ 
class SomeEntity 
{ 
    ... 

    /** 
    * @PreUpdate 
    * @PrePersist 
    */ 
    public function preUpdate() 
    { 
     // This function is called every time this model gets updated 
     // or a new instance of this model gets persisted 

     // Somethink like this maybe... 
     // I have not yet completely thought through all this. 
     $cache->save(get_class($this) . '#' . $this->getId(), $this); 
    } 
} 

所以也許這可以用來使實體的每一個實例失效?

+0

您沒有回答我的問題... – Nanocom