PHP PEAR Cache_Lite

HI.

Since I m using shared hosting package, and im not able to use PECL Memcache, i would appreciate some tips about my own doubt between using my own little caching system or using PEAR Cache_Lite system.

So here are my functions:

<?php

//this one create a simple .txt file named by unique query_key string generated width e.g $file_name=md5("SELECT * FROM table"); content of that file is serialized value of mysql return

function write($query_key,$result)
{
  global $config;
  $new_file_name=md5($query_key);
  $result_to_write=serialize($result);  
  if($handle=opendir($config['cache_dir'])) 
  {
    $f=fopen($config['cache_dir'].$new_file_name.'.txt','w+');
    fwrite($f,$result_to_write);        
    fclose($f);
    closedir($handle);
  }
}

// this one reads content of file (serialized mysql return of unique query_key) if timeout hes not expired, and if it is it return false

function read($query_key,$timeout)
{
  global $config;
  $file_name=md5($query_key);
  if($handle=opendir($config['cache_dir'])) 
  {
    if(file_exists($config['cache_dir'].$file_name.'.txt'))
    {
      $last_accessed=filemtime($config['cache_dir'].$file_name.'.txt');
      $now=time();
      if(($now-$last_accessed)<$timeout)
      {
        $file=fopen($config['cache_dir'].$file_name.'.txt','rb');
        $f=fread($file,filesize($config['cache_dir'].$file_name.'.txt'));
        $array=unserialize($f);
        fclose($file);  
        closedir($handle);
      }else{ return FALSE; }
    }else{ return FALSE; }
  }
  if(!empty($array)) return $array;
  else return FALSE;
}

//and finally this one which is used when executing query, so it has timeout in seconds, if file (cached result) exists, and timeout has not expired, it returnt cached data , or it reads from database returns new result,and cache new result by writing new file

function cache($query)
{
  $timeout=600;
  $file_exists=read($query,$timeout);
  if($file_exists)
  {
    return $file_exists;
  }else{
    $result=get_rows($query);
    write($query,$result);
    return $result;
  }
}
?>

This my little "caching system" works very good, and as i can see, PEAR Cache_Lite works almost same way, and as i'm not familiar with pear cache system, i would like to know what is better, safer and faster solution to use between those two, and why??

Thanx a Lot!!

Personally, I would use a library for this. Writing a caching layer is a lot harder that it seems. It's not so hard that you can't do it, but it's hard to get all the edge cases and quirks out of the system. You can use something like Cache_Lite, but I would suggest a better caching layer. There are a few of them out there (both standalone and framework born). Here are a few:

  • Zend_Cache - You can use this standalone. But it also is pretty well designed and tested...

  • Cache_Lite - if you only want file caching. It's light weight, but also not terribly flexible (but that may be what you want).

  • Kohana's cache. It's fairly flexible, but I'm not so sure how easy it will be to separate from the rest of the framework (no experience with it).

A few comments about your code:

  1. I would use different variable names. $file_exists in the cache() function is a really poor name for what it does. It should be something like $cache_results. Use semantic meaning to identify your names.

  2. I would really wrap this in a class so you can better do initialization. There are some things you only want to do once per request, so there's no need to do it every time (more on that in a bit).

  3. Clear your stat cache! Run clearstatcache() once per request. The reason is that PHP can cache invalid stat information and return wrong information for file_exists, filemtime, etc. But it's fairly expensive, so I wouldn't run it more than once per request...

  4. There's no need to use opendir at all in read() or write(). If you want to verify that the directory exists, just call is_dir($dir). Right now, you're opening an handle and doing nothing with it.

  5. You have a resource leakage in both read() and write() where there are paths where you open the directory but do not close it. While this won't be a huge deal most of the time, close your resources properly. (better yet, eliminate the calls altogether).

  6. Don't use fopen(); fwrite(); fclose(); for this type of operation. You could be shooting yourself if another request comes in while you're writing to the file (which will result in a partial read). Instead, use file_put_contents($filename, $data, LOCK_EX); for writing. It's basically atomic (not quite, but close enough for your purposes). And I would lock the file before reading it in read():

    $file=fopen($config['cache_dir'].$file_name.'.txt','rb');
    if (flock($file, LOCK_SH)) {
        $f=fread($file,filesize($config['cache_dir'].$file_name.'.txt'));
        flock($file, LOCK_UN);
    }