Using sfFileCache directly

You can configure a lot of caching in symfony, so rarely do you need to cache things yourself, but it may happen that one day you decide you need it. I came to that point when I wanted to cache certain results from external web services. I could have used the Function caching, but in this case I wanted to keep a bit more control, possibly altering the cache etc.

To do this I wrote a little wrapper class that contained three little methods, but that opened up the symfony file cache for my own usage. I wanted to ensure I didn't end up with tons of cache objects, so first I implemented a method that would only create a new cache object if I didn't have one already, or else just return the object:

  public static function getCacheObject() {
    if (!self::$cache instanceof sfFileCache) {
      $file_cache_dir = sfConfig::get('sf_cache_dir' ;) . '/my_own_filecache';
      self::$cache = new sfFileCache($file_cache_dir);
    }
    return self::$cache;
  }

as you see, the cache is being written in a directory called /my_own_filecache inside the symfony cache dir. I could save this everywhere of course, just decided this would be a good place. Note: if you do a symfony cc then your cache will also be cleared, so if you want this not to happen, place your cache directory outside of symfony's cache directory.

Then I need a way to set something in the cache:

  public static function setToCache($namespace, $name, $value) {
    $file_cache = leftTools::getCacheObject();
    $file_cache->setLifeTime(3600);
    $file_cache->set($name, $namespace, serialize($value));
  }

I set the lifetime of the cached value hard to 3600 seconds, but this could of course be dynamic. In my case, this is enough. I serialize the value myself, as I used to have some trouble with objects being cached. I'm actually not sure if it's still needed, as there were more problems with the objects. I'll leave it in for now ;)

And of course, what you set, you'll want to get, so here is the getter:

  public static function getFromCache($namespace, $name) {
    $file_cache = leftTools::getCacheObject();
    if ($file_cache->has($name, $namespace)) {
      $cached = $file_cache->get($name, $namespace);
      if (!empty($cached)) {
        return unserialize($cached);
      }
    }
  }

Well, this is pretty simple. I only return something if there is something to return, and I unserialize before returning.

Using the sfFileCache is pretty simple as you can see. Use it to your advantage. 


Add comment

Comments

gravatar thibault: Thank you a lot. You helped me power up my symfony app !
February 20, 2008
gravatar Markus: maybe this article could also be interessting for you
http://redotheweb.com/2007/03/16/build-your-own-feed-aggregator-with-symfony/
February 20, 2008
gravatar Peter: Helped me out for sure. Thanks. Thumbs up on stumble :mad:
August 26, 2008
gravatar rexxy: thanks, was looking for something like this :)
April 12, 2009

Php5_zce_logo

not tested in IE


Upcoming events

I will be speaking 04-09-2009: Symfony Day 2009

Tags

1337 2008 4developers accessibility AdaLovelaceDay09 agavi agile amsterdam apache apple article articles atk atkMetaNode audioscrobbler backwards compatibility bbc beatstad best practices bittorrent book books bughuntday caching cake cal evans cat cerf certificate cfp clear cms community conference conferences continuous integration crisis css custom DbFinderPlugin decorator decorators deployment devdays development directoryindex documentation download dpc dpc09 DPC2008 dreamhost eclipse ed efficiency enterprise event events expertise ezcomponents flickr frameworks freeze frontend fun games germany getting real google googletalk graceful degradation hack hackers hidden gem howto html http ibuildings icann ide imovie indy internet IPC ipc ipc08 javascript jobeet john peel joomla left on the web lime linux live london loudblog m2ts mac malware mambo marjolein meme meta methodology microsoft movie music mysql namespace namespaces nllgg odmarco open source ORM osx paradiso pear personal pfcongrez photo php phpabstract phpBB phpbb phpbelgium phpbenelux phpgg phpitalia phpnw phpnw08 phptek phptek09 phpuk2009 phpUnderControl phpunit php|architect php|tek podcast politics portability postcrossing presentation presentations public qa recruiting refactoring review rewrite ruby on rails schedule script security seven things simplexml slides software sogeti solar standard standards static steer strings subversion symfony symfonycamp symfonyUnderControlPlugin talk technology techportal tek09 terratec terrorism testfest testing textpattern tips tld tomas usability usergroup vhost video vinyl virus warp weblogging wiki women world world of warcraft writing xml xpath yara year youtube ZCE zemanta zend zend framework zend server zend studio Zend_Form
© 2004 - 2009 Stefan Koopmanschap + Powered by Symfony, photos powered by Flickr, links powered by Delicious, Shanghai smilies by Iconbuffet. Feeds: rss / atom. Left on the Web v4.4.0