Tito Miguel Costa
Refactoring ideas

Cache Data in Symfony2

Use Doctrine library to cache data in Symfony2

Doctrine provides a Cache Layer. 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.

$cache = $this->get('cache');
$cache->setNamespace('mynamespace.cache');

if (false === ($cached_data = $cache->fetch($cache_key)))
{
    $cached_data = $SOMEAPI->getData($params);
    $cache->save($cache_key, $cached_data, 3600);//TTL 1h
}

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.

Original source
23 November, 2012
Tutorial
Symfony2, Doctrine, Cache

Comments