Caching Data in Symfony2

Symfony2 has a great Caching Layer based on its HTTP Cache. But this aims mainly on caching the views.

In some apps however you need to cache data behind the scenes, f.e. responses from API calls or custom objects sets.
Symfony2 itself doesnt have such a functionality on first sight (symfony2 doesnt, but Doctrine, see below) and so I searched for one and first found a bundle which utilize the Zend Cache lib:
https://github.com/KnpLabs/KnpZendCacheBundle

This worked well but as discussed here(https://github.com/KnpLabs/KnpZendCacheBundle/issues/2) this adds dependencies to your Symfony2 project. This is actually not necessary since Doctrine/Commons is almost always part of your Symfony2 distribution and the Doctrine/Commons provides a Cache Layer as well.
A very good one, indeed.

So if you need to cache data use Doctrine/Commons.

This Cache Layer abstracts the caching functionality and provides already various different backends for your caching data.
These are already build-in in the master version:

  • APC
  • Array
  • Filesystem
  • Memcache
  • PhpFile
  • Redis
  • WinCache
  • Xcache
  • ZendData

You could even create your own on top of the CacheProvider class and the Cache interface.

In your Symfony2 project simply register your cache service of choice and your ready to go.
In your config.yml or services.yml add:

cache:
        class: Doctrine\Common\Cache\PhpFileCache
        arguments: [%kernel.cache_dir%]

And in your controller you can call the service and save and load data from the cache.

As you can see you can set a namespace for your cache data, so that you can easy use it for different scenarions in the same app.
Further you can set a time-to-live (TTL) in seconds as third parameter of the save method.

So after all symfony2 has a caching mechanism for data, its just a little hidden in the Doctrine/Commons dependency.

Update from the Update!!
LiipDoctrineCacheBundle is abanndoned, use https://github.com/doctrine/DoctrineCacheBundle
Update!!
————————————————————-

I just was told that there is a Bundle for the Doctrine/Commons cache:
https://github.com/liip/LiipDoctrineCacheBundle

So I recommend to use this.
The benefit of this is, you can configure your caches through yml files and you have one central cache reference. I guess this saves some bytes in case you use different caches with different namepaces.

So with the LiipDoctrineCacheBundle the above example would go like this (given you have already registered the bundle):

config.yml

liip_doctrine_cache:
    namespaces:
        mynamespace:
            namespace: mynamespace.cache
            type: php_file

IndexController.php

$cache = $container->get('liip_doctrine_cache.ns.[mynamespace]');
if (false === ($cached_data = $cache->fetch($cache_key))) {
            $cached_data = $SOMEAPI->getData($params);
            $cache->save($cache_key, $cached_data, 3600);//TTL 1h
}

7 Replies to “Caching Data in Symfony2”

Comments are closed.