caching - 原则 2 结果缓存失效

标签 caching doctrine-orm apc cache-invalidation

我在查询中使用 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/

相关文章:

javascript - 在缓存应用程序(缓存 list )之前,我是否必须打开 iOS 网络应用程序?

ios - iOS 可以只删除我的应用程序缓存文件夹的一部分吗?

php - 为时间敏感的图像覆盖 Gmail 图像缓存(或设置较短的时间限制)

php - Symfony 身份验证(您不能从 EntityUserProvider 刷新用户)

php - 两个捆绑关系中的 Symfony2 "class not found in the chain"

php - PHP 操作码与实际执行的二进制代码有何关系?

caching - 我的页面是否必须具有 HTML5 文档类型才能访问 sessionStorage

symfony - Symfony 2 中相关实体的急切加载

PHP APC - 共享托管中是否有替代或手动流程?

php - 具有多个客户端并防止缓存踩踏的 PHP Web 服务的最佳方法