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:
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.
2 replies on “A note on symfony caching”
sfFunctionCache is cool. I extends this class to cache propel object.
A quick headsup: the formatting of the code samples is broken on Safari.