Reputation: 18660
I use Doctrine Entity Manager in my code several times, I used in this way for example:
$em = $this->getDoctrine()->getManager();
$countries = $em->getRepository('CommonBundle:Country')->findAll();
It's possible to use Doctrine Cache in this format? I see a lot of docs but all of them relative to Doctrine Query Builder, any advice? How to enable cache for SELECT
queries?
Caching is not working (tough)
I'm dealing with caching results and I do this in order to cache some queries:
Enable APC under orm
configuration at config.yml
:
doctrine:
dbal:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
orm:
auto_generate_proxy_classes: "%kernel.debug%"
auto_mapping: true
metadata_cache_driver: apc
result_cache_driver: apc
query_cache_driver: apc
Attach a repository to my entity:
/**
* @ORM\Entity(repositoryClass="CommonBundle\Entity\Repository\CountryRepository")
*/
class Country {
....
Write a method inside repository class for get the data and cache the results:
public function getCountries() {
$qb = $this->createQueryBuilder('c');
$query = $qb->getQuery();
$query->useResultCache(true, 3600, 'countries_cache');
return $query->getResult();
}
But any time I reload the page the query is executed as shown in the profiler (see picture below):
What I did wrong? The cache only works for production or also works for development? Should't get cached results instead of query the database once and once?
Upvotes: 0
Views: 2739
Reputation: 12717
EntityRepository API does NOT allow to enable ResultCache with find* methods.
You have to use a QueryBuilder and/or DQL requests.
I wrote an article about Doctrine caching, maybe it can help you : http://blog.alterphp.com/2014/05/doctrine2-optimization-with-apc-cache.html
Upvotes: 2
Reputation: 1181
You have to enable cache for results in your symfony configuration :
doctrine:
orm:
metadata_cache_driver: apc # or memcache
result_cache_driver: apc # or memcache
query_cache_driver: apc # or memcache
Then on every request that need to be cached, call
$query->useResultCache(true)
More advanced options available here : http://docs.doctrine-project.org/en/2.0.x/reference/caching.html#result-cache
Upvotes: 1