How to cache in Symfony 2?

Solution 1:

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));
}

Solution 2:

Simple way use Doctrine cache providers. At first, register service(sample in config.yml):

services:
    memcached:
        class: Memcached
        calls:
            - [ addServer, ['localhost', 11211] ]
    memcached_cache:
        class: Doctrine\Common\Cache\MemcachedCache
        calls:
            - [ setMemcached, [@memcached] ]

Then to use get service, for example in controler:

$cache = $this->get('memcached_cache');

to send in another service use calls:

calls:
    - [ setCacheProvider, [@memcached_cache] ]

or arguments:

arguments:
    - @memcached_cache

In the same way, you can use other interfaces of Doctrine Cache package. Doctrine Cache provides a very simple interface for which several out of the box implementations are provided:

  • ApcCache (requires ext/apc)
  • ArrayCache (in memory, lifetime of the request)
  • FilesystemCache (not optimal for high concurrency)
  • MemcacheCache (requires ext/memcache)
  • MemcachedCache (requires ext/memcached)
  • PhpFileCache (not optimal for high concurrency)
  • RedisCache.php (requires ext/phpredis)
  • WinCacheCache.php (requires ext/wincache)
  • XcacheCache.php (requires ext/xcache)
  • ZendDataCache.php (requires Zend Server Platform)

If you do not already use Doctrine, you may require Common Library for Doctrine projects: php composer.phar require doctrine/common or require only Caching library offering an object-oriented API for many cache backends: php composer.phar require doctrine/cache

How to use Doctrine Caching you can read in Doctrine Common documentation on Doctrine Project web site

Solution 3:

Symfony 3.1 provide a new Cache component.