Nov 28
Digg
Stumbleupon
Technorati
Delicious

A note on symfony caching

Symfony has some great built-in caching mechanisms enabled by default. But obviously if you have data which is rarely changing you would want to cache it additionally.
Lets consider situation when you need to cache some array (which may be itself selection from DB), so easiest way to cache it in symfony is to use sfFileCache object:

    $c = new sfFileCache(array('cache_dir' => sfConfig::get('sf_cache_dir')));
    $c->set('myarray', serialize($myarray));

where $myarray is cached array and in order to retrieve it from cache we use:

    $c = new sfFileCache(array('cache_dir' => sfConfig::get('sf_cache_dir')));
    $myarray = unserialize($c->get('myarray'));

If you need to clean out cache (e.g. when you changed DB value and need to re-read table for re-caching):

    $c = new sfFileCache(array('cache_dir' => sfConfig::get('sf_cache_dir')));
    $c->remove('myarray');

Obviously it should not be necessarily array, you can cache e.g. object or objects collection.

In order to change cache object lifetime you can use method setLifeTime:

$c->setLifeTime(3600)

If you are getting serious about caching you may need to have a look into other caching classes like sfFunctionCache (for caching methods), sfMemcacheCache (for caching using memcache), etc.

Good luck!


Author: symfonian

2 Comments

nibsirahsieu
November 28, 2010

sfFunctionCache is cool. I extends this class to cache propel object.

James Lewis
December 2, 2010

A quick headsup: the formatting of the code samples is broken on Safari.

Comments RSS TrackBack Identifier URI

Leave a comment