Make Doctrine use result cache by default

♀尐吖头ヾ 提交于 2019-12-03 17:05:26

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:

<?php
class CachedEntityManager implements EntityManagerInterface { 

private $proxiedManager;

public function __construct(EntityManagerInterface $proxiedManager) {   
    $this->proxiedManager = $proxiedManager;    
}

public function createQuery($dql = '') {
    $query = $this->proxiedManager->createQuery($dql);
    $query->useResultCache(true);   
}

[... proxy all the calls forth to proxiedManager ...]

}

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) :

<?php
class CachedEntityManager extends EntityManager { 

public function createQuery($dql = '') {
    $query = parent::createQuery($dql);
    $query->useResultCache(true);   
}

}

Create a wrapper class/function that explicitly sets useResultCache(true) and use that everywhere instead of the native function.

You can hack the Doctrine core a little by setting the default value of $_useResultCache to TRUE 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!