Tuesday, May 13, 2014

Doctrine2 optimization with APC cache and Symfony2

Some parts of a website are common to every pages and needs to request data from database. To put this data in a cache system is often a first step for optimization. Here is my return on experience about caching data with Doctrine2 in a Symfony2 project.


Before caching data, deal with metadata

Doctrine metadata store informations about entities structure, relations and so on. It's really safe to put in cache memory because it's nearly never changed. Have a look to the config in app/config/config_prod.yml :

# Doctrine Configuration
doctrine:
    dbal:
        ...
    orm:
        metadata_cache_driver: apc

(Still) Before caching data, deal with queries

Doctrine2 uses DQL, its own meta language to generate SQL queries. When you use a QueryBuilder or directly writes your queries in DQL, SQL query is generated each time data are requested. Next config allows Doctrine2 to put generated SQL in cache too. Have a look to the config in app/config/config_prod.yml :

# Doctrine Configuration
doctrine:
    dbal:
        ...
    orm:
        metadata_cache_driver: apc
        query_cache_driver: apc

Finally caching data !