Using sfFileCache directly

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->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.