Simple caching in PHP5

I’ve just written a script that reads from a few webpages and I faced a problem of the servers sometime being slow and delaying my page display, so I decided to write a simple caching object:


class cache {

    function __construct($path='.') {
        $this->path = $path;
    }

    function cache($name, $callback, $args) {
        if (file_exists("$this->path/$name")) {
            $this->callbacks[$name] = array($callback, $args);
            return implode('', file("$this->path/$name"));
        } else {
            return $this->save($name, $callback, $args);
        }
    }

    function save($name, $callback, $args) {
        $text = call_user_func($callback, $args);
        $fh = fopen("$this->path/$name", 'w');
        fwrite($fh, $text);
        fclose($fh);
        return $text;
    }

    function __desctruct() {
        if (is_array($this->callbacks)) {
            foreach ($this->callbacks as $name => $callback) {
                list($callback, $args) = $callback;
                return $this->save($name, $callback, $args);
            }
        }
    }
}

You call it using:

$cache = new Cache();
$cache->cache('MyFunc.txt', 'MyFunc', 'an argument');

All it does is save the output of the function to a file with the given name. The clever bit is that the output it sends to the browser is the content of the file; it doesn’t actually call the function until the end of the script execution and so doesn’t slow the output to the browser down.

  • Start sending output.
  • Output cached result of function.
  • Finish sending output.
  • Call function and save to the cache file.

It means the content will always be slightly out of date, but in a lot of situations that may not be a problem. Quick note, this is only really possible (at least the way I’ve done it) in PHP5 because it requires destructor support.