我在查询中使用 Doctrine 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();
}
这样我就不需要在网站的每个页面上进行无用的查询。
我的问题:这是推荐的做法吗?我最终会遇到问题吗?
最佳答案
我有一个想法来构建一个 onFlush 钩子(Hook)。 在那里,所有实体都排队等待插入、更新和删除,因此您可以根据实体名称和标识符等使缓存失效。
不幸的是,我还没有构建任何事件监听器,但我绝对计划为我的项目构建这样的东西。
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);
}
}
那么也许这可以用来使实体的每个实例无效?
关于caching - 原则 2 结果缓存失效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11171829/