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
gravatar Cannon Courier news source: This is very useful info regarding software and helps us a lot to increase our knowledge regarding this topic. Thanks for sharing such nice and informative post here.
June 4, 2011
gravatar Cheap stickers availability: Well such type of documented issues are good enough to be discussed here. So bundle of thanks for sharing them here, as it is kind of an amazing addition for all of us. Keep updating us
June 8, 2011
gravatar orlando networking: I think this works so good. There is so much that you can get from this. Keep up the good work.
November 3, 2011
gravatar 5 htp supplement cost: of the cached value hard to 3600 seconds, but this could of course be dynamic.
November 30, 2011
gravatar clarinet overhaul cost: So bundle of thanks for sharing them here, as it is kind of an amazing addition for all of us. Keep updating us

November 30, 2011
gravatar dimethylamylamine dmaa: So bundle of thanks for sharing them here, as it is kind of an amazing addition for all of us. Keep updating us
November 30, 2011
gravatar yohimbine hci: 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,
November 30, 2011
gravatar shizandrol dose: just decided this would be a good place. Note: if you do a symfony cc then your cache will also be cleared,
November 30, 2011
gravatar ikpdsvaj: of the cached value hard to 3600 seconds, but this could of course be dynamic.

December 23, 2011
gravatar bose ie2 review: aaaaa
January 8, 2012
gravatar bose ae2 review: asdadad
January 8, 2012
gravatar bose bluetooth headset review: adsadadadad
January 8, 2012
gravatar bissell steam and sweep reviews: asadadad
January 8, 2012
gravatar gaming laptop reviews: asdadasdasdasd
January 8, 2012
gravatar numark mixtrack pro review: asdasdadsasdasds
January 8, 2012
gravatar modern furniture stores phoenix:
I enjoy a lot of good data. I really am impressed with your content and I feel I have learned something by reading this article
January 26, 2012
gravatar modern furniture stores phoenix:
Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any ways I'll be subscribing to your feed and I hope you post again soon.
January 30, 2012
gravatar What is pancreatic cancer: . .
Wow! This can be one of the most useful blogs we have ever come across on thesubject. Basically magnificent info! I'm also a specialist in this topic so I can understand your hard work.
January 31, 2012
gravatar discount uggs boots: I am typically to running a blog and i really respect your content. The article has really peaks my interest. ;)
February 1, 2012
gravatar michael michael kors: Great post I hope to see more, keep up the good work.

February 2, 2012

Php5_zce_logo

Upcoming events

I will be speaking 06-02-2012: D-Day
I will be speaking 17-02-2012: Techademy Trainingday February
I will be speaking 23-02-2012: Zend Webinar: Git for Subversion Users

Tags

1337 2008 2010 2011 4developers access modifiers accessibility AdaLovelaceDay09 advent agavi agile alfred amsterdam apache api apple article articles atk atkMetaNode audioscrobbler automation azure backwards compatibility barcelona barcodes bash bbc bbq beatstad belgium best practices bittorrent blogging blogs boards of canada book books bughuntday bundle caching cake cal evans calendar career cat cerf certificate cfp clear cms cologne common sense communities community components conference conferences contest continuous integration contribute contribution crisis css custom d-day datetime DbFinderPlugin decorator decorators deployment devdays development directoryindex docblox doctrine documentation download dpc dpc09 dpc10 dpc11 DPC2008 dreamhost drupal dv7 eclipse ed editors efficiency enterprise errors event events expertise ezcomponents facebook finland flickr fork framework frameworks freelance freeze frontend fun game games geoip germany getting real git github gnome-do google google calendar googletalk graceful degradation hack hackers hidden gem hiphop howto hp HR html http i386 ibuildings icann ide ideasofmarch idm imovie indy ingewikkeld integration international php conference internet interview ipad IPC ipc ipc08 ipc10 ipc11se iterm2 javascript jenkins jenkins-php job job openings jobeet john peel joomla joomladays kiva kubuntu launcher launchy left on the web libraries library lighttpd lime linktuesday linux live london loudblog m2ts mac magazines malware mambo marjolein mediterra meeting meme meta methodology micro-financing microframework microsoft migration movie music mysql namespace namespaces netbeans netherlands newsfire nllgg nos odmarco open source opinion ORM osx paradiso paris partnership pavilion pear pecl performance personal pfc10 pfc11 pfcongres pfcongrez pfz photo php php5.3 phpabstract phpazure phpBB phpbb phpbelgium phpbenelux phpbnl10 phpday phpdoc phpdocumentor phpgg phpitalia phpnw phpnw08 phpnw11 phpstorm phptek phptek09 phpuk2009 phpUnderControl phpunit php|architect php|tek podcast politics portability postcrossing presentation presentations private projects protected prototype PSR-0 public python qa qr codes re2c recruiting refactoring review rewrite ruby on rails san francisco schedule scifi script security sensio seven things sfdaycgn sflive2011 shell scripting silex simplexml slides smfony software sogeti solar sound speakers spl ssh standard standards star trek static steer strings stylesheets subversion symfony symfony live Symfony2 symfonycamp symfonyday symfonylive symfonyUnderControlPlugin talk talks techademy technology techportal tek09 telecommuting terratec terrorism testfest testing textmate textpattern the right tool timeout tips tld todo tomas tools training twig uncon unet usability usergroup validation vhost video vim vinyl virus warp webinar weblogging webservices wiki windows winphp women wordpress work workshop world world of warcraft wpi writing wunderlist xml xpath xsd yara year youtube zc11 ZCE zemanta zend zend framework zend server zend studio zendcon Zend_Form zite
© 2004 - 2012 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.1