Implementing Doctrine Caching with Memcached in Symfony 2

 

Doctrine 2 has a full chapter devoted to caching, but I found some issues when I tried to implement this feature in Symfony 2 because I couldn’t find any clear documentation about the subject.

I will explain how to do it with memcached in an ubuntu machine, but there is no big difference on doing it wit any cache driver (as APC, Xcache, etc).

Doctrine use three types of cache:

  • Query Cache: This cache saves the transformations of a DQL query to its SQL counterpart. It doesn’t make sense to do this parsing multiple times as it doesn’t change unless you alter the DQL query.
  • Metadata Cache: Your class metadata can be parsed from a few different sources like YAML, XML, Annotations, etc. Instead of parsing this information on each request we should cache it using one of the cache drivers.
  • Result Cache: This cache can be used to cache the results of your queries so that we don’t have to query the database or hydrate the data again after the first time.

Lets dive into the configuration for this.

First of all install the memcached php extension.

~ # > aptitude install php5-memcached

After that you will need to configure the memcached servers parameters

//app/config/parameters.yml
parameters:
    ...
    memcache_hosts:
        -
            dsn: 127.0.0.1
            port: 11211

Next we need to create some services

services:
    memcached:
        class: Memcached
        calls:
            - [ addServers, [%memcache_hosts%] ]

    doctrine.cache.memcached:
        class: Doctrine\Common\Cache\MemcachedCache
        calls:
            - [ setMemcached, [ @memcached ] ]

After that we will need to add some configuration to config.yml

//app/config/config.yml

...
doctrine:
    ...
    orm:
        entity_managers:
            default:
               ...    
               metadata_cache_driver:
                    type: service
                    id: doctrine.cache.memcached
                query_cache_driver:
                    type: service
                    id: doctrine.cache.memcached
                result_cache_driver:
                    type: service
                    id: doctrine.cache.memcached

Now We can use Memcached to cache our queries as the Doctrine Doc explains.

Also we have three symfony commands to clear the doctrine cache

$> php app/console doctrine:cache:clear-metadata 
                 //Clears all metadata cache for an entity manager
 
$> php app/console doctrine:cache:clear-query 
                 //Clears all query cache for an entity manager

$> doctrine:cache:clear-result 
                 //Clears result cache for an entity manager

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.