让 Doctrine 默认使用结果缓存
我将 Memcache 绑定到 Doctrine,似乎我必须在每个查询中显式地 useResultCache
。是否可以默认设置为 true
,并在不需要时使用 useResultCache(false)
?
I'm binding Memcache to Doctrine and it seems I have to useResultCache
explicitly in every query. Is it possible to make it true
by default, with the ability to useResultCache(false)
where it's not needed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
创建一个显式设置
useResultCache(true)
的包装类/函数,并在各处使用它而不是本机函数。Create a wrapper class/function that explicitly sets
useResultCache(true)
and use that everywhere instead of the native function.我知道这个问题已经很老了,但我会写下我想到的最佳答案。
1)抽象出对接口的依赖(即 - 使用依赖注入模式将 EntityManager 注入到创建查询的类中,并使用 EntityManagerInterface )
现在,要么:
a)[更好,但更长]为 EntityManagerInterface 创建一个新的与组合相关的实现,这将代理对原始实体管理器的调用,并将结果缓存标志设置为 true:
b) [ 不太好,但更短 ] 扩展 EntityManager 类并覆盖 createQuery。请记住,这通常不是一个好的做法,您绝对不应该再在该类中编写任何内容,而是重构为 a) :
I know this question is old, but I'll write up the best answer that comes into my mind.
1) Abstract away your dependency to interface ( i.e. - use dependency injection pattern to inject EntityManager into your class that creates queries and use EntityManagerInterface instead )
Now, either:
a) [ Better, but longer ] Create a new composition-related implementation for EntityManagerInterface, that will proxy calls to original entityManager and will set result cache flag to true:
b) [ Not as good, but shorter ] Extend the EntityManager class and override the createQuery. Remember that this in general is not a good practice and you should definitely not write anything in that class anymore but instead refactor into a) :
您可以通过将
\Doctrine\ORM\AbstractQuery
中的$_useResultCache
默认值设置为TRUE
来破解 Doctrine 核心。这将使所有查询默认使用 resultCacheDriver,并且您可以使用$query->useResultCache(FALSE)
轻松关闭单个查询的缓存。这是一个有用的小技巧,可以为您节省大量时间打字,但要小心;我发现缓存驱动程序不会缓存尚未初始化的延迟加载关联(现在我想起来这一点很明显)。有时,为每个单独的查询打开结果缓存会更安全。
You can hack the Doctrine core a little by setting the default value of
$_useResultCache
toTRUE
in\Doctrine\ORM\AbstractQuery
. This will make all queries use the resultCacheDriver by default, and you can easily turn the cache off for individual queries using$query->useResultCache(FALSE)
It's a useful little hack that saves you a lot of typing, but be careful; I've found that the caching driver won't cache lazy-loaded associations that haven't been initialized (which is obvious now I think about it). Sometimes it's safer to just turn result caching on for each individual query.