Doctrine 2结果缓存失效

9

我正在使用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();
}

为了避免在网站的每个页面上进行无用的查询。我的问题是:这是一个推荐的做法吗?我最终会遇到问题吗?
2个回答

2
我有一个构建onFlush钩子的想法。在那里,您可以获取所有排队进行插入、更新和删除的实体,因此可以根据实体名称和标识符等使缓存无效。
不幸的是,我还没有构建任何事件监听器,但我肯定计划为我的项目构建这样的东西。 这里 是Doctrine文档中关于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

这是我偶然发现的一个旧问题。如今使用Doctrine 2.8非常简单:

/** @var \Psr\Cache\CacheItemPoolInterface|null $cache */
$cache = $em->getConfiguration()->getResultCache();

$cache->deleteItem('skepin_messaging.nbNewMessages.'.$userId);
$cache->clear(); // clear all items

请注意,Doctrine内部生成一个“真实的缓存键”,它看起来与您的不同。我不知道如何生成该缓存键,而不重新创建已使用的查询。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接