Symfony2 caching Doctrine2 results

There are many options developer can use for speeding up web application. But you already knew that…
Let’s skip long introduction and show by example:
Inside Symfony2 project it’s really easy to use all three types of cache with Doctrine2:
metadata cache, query cache and result cache.
First of all, you have to make sure that cache is available within your hosting provider. In this example I will use APC cache assuming that it’s installed and properly configured on server:
#app/config.yml
#...
# Doctrine Configuration
doctrine:
#...
orm:
auto_generate_proxy_classes: %kernel.debug%
#auto_mapping: true
default_entity_manager: default
entity_managers:
default:
metadata_cache_driver: apc
result_cache_driver: apc
query_cache_driver: apc
connection: default
mappings:
SurgeworksCoreBundle: { type: annotation, dir: Entity/ }
#...
So like you can see in this example, you just have to write cache driver name that is used under entity manager section of your ORM configuration – in our case it’s apc.
After configuration is ready let’s make a little test:
//SomewhereInsideController
//...
$em = $this->get('doctrine.orm.entity_manager');
$q = $em->('SELECT i FROM Surgeworks\CoreBundle\Entity\ItemsToCollections i);
//We can do this to check what driver is currently used:
//print_r($q->getResultCacheDriver());exit;
//Or just enable our result caching …
$q->useResultCache(true, 3600, 'somecache_id');
//You can skip this cache id and id will be automatically generated...
$result = $q->getResult();
//...
So, useResultCache accept three parameters:
1. If you want to use caching for result then set: true
2. Second is cache lifetime
3. Optional paramete where you can set unique cache id (if ommited, id will be automatically generated).
I hope that you will find this article useful in your own project….
Cheers!
2 comments
Keep in mind if your development environment and production environment use different databases, that the result cache will display the results for the environment that is loaded first, unless you apply a condition to generate a different cache id based on the environment.
Nice article, however I needed to cache a doctrine query builder and it’s slightly different. There is no too much info so
here it is, hope it helps: