Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Doctrine use result cache by default

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?

like image 397
Fluffy Avatar asked Dec 05 '22 22:12

Fluffy


2 Answers

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

like image 72
Byron Whitlock Avatar answered Feb 03 '23 10:02

Byron Whitlock


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

}
like image 23
user1009783 Avatar answered Feb 03 '23 09:02

user1009783