【问题标题】:Doctrine 2 result cache invalidationDoctrine 2 结果缓存失效
【发布时间】:2012-06-23 18:12:19
【问题描述】:

我在一个查询中使用 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();
}

这样我就不需要在我网站的每个页面上进行无用的查询了。

我的问题:这是推荐的做法吗?我最终会遇到问题吗?

【问题讨论】:

    标签: caching doctrine-orm apc cache-invalidation


    【解决方案1】:

    我有构建一个 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);
        }
    }
    

    所以也许这可以用来使实体的每个实例无效?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-14
      • 2017-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-03
      相关资源
      最近更新 更多