Search code examples
phpcachingserializationsymfony1symfony-1.4

Code generation for caching purposes


I need to cache the results of a very expensive operation that involves scanning a directory and getting the contents of its files.

A good way to solve the problem is to cache the result in a php files. Since php files are loaded very quickly, I was thinking about serializing the whole array of result in a php-valid form, written to disk and ready to be included.

My question is: are there any tools/libraries/frameworks that perform the task of serialization in php code for caching purposes? If not, what are the best practices to achieve this?

EDIT:

Thanks Jack for var_export!

Any ideas for how to add some code to the symfony cc in order to trigger the generation of this cache?


Solution

  • Use symfony's sfCache class. It can store and retrieve objects, and use various cache backends (you can use files, databases or APC as the backend)

    Usage is simple: (I'm using APC as cache storage, as APC is already enabled on my server. If you want to store data in files you can use sfFileCache)

    $cache = new sfAPCCache();
    if ($cache->has('data')) {
      return $cache->get('data');
    } else {
      $data = calcualte_data();
      $cache->set('data',$data);
      return $data;
    }