Make Doctrine use result cache by default

2019-04-02 00:52发布

问题:

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?

回答1:

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);   
}

}


回答2:

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



回答3:

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.