How to cache in Symfony 2?

If you are using Doctrine already just use those cache classes.

Add a service to config.yml:

services:
    cache:
        class: Doctrine\Common\Cache\ApcCache

And use it in your controller:

if ($fooString = $this->get('cache')->fetch('foo')) {
    $foo = unserialize($fooString);
} else {
    // do the work
    $this->get('cache')->save('foo', serialize($foo));
}

Leave a Comment