Any decent PHP framework must have some kind of caching mechanism to reduce the overhead caused when accessing a database server or serving static pages, and the one that I’m building here is no exception. For this particular project, the caching system will be a regular class that will use the file system for caching data. Having explained that, here’s the partial definition of the cache class: class Cache { private $cachedir = 'cache/'; private $expire = 60; private static $instance = NULL;
// get Singleton instance of Cache class public static function getInstance($cachedir = '') { if (self::$instance === NULL) { self::$instance = new self($cachedir); } return self::$instance; }
// constructor public function __construct($cachedir = '') { if ($cachedir !== '') { if (!is_dir($cachedir) or !is_writable($cachedir)) { throw new Exception('Cache directory must be a valid writeable directory.'); } $this->cachedir = $cachedir; } }
// write data to cache file given an ID public function set($id, $data) { $file = $this->cachedir . $id; if (file_exists($file)) { unlink($file); } // write data to cache if (!file_put_contents($file, serialize($data))) { throw new Exception('Error writing data to cache file.'); } }
// read data from cache file given an ID public function get($id) { $file = glob($this->cachedir . $id); $file = array_shift($file); if (!$data = file_get_contents($file)) { throw new Exception('Error reading data from cache file.'); } return unserialize($data); } } As you can see above, the “Cache” class defines a couple of methods that can be used for writing data to the file-based cache and for reading from it. This two-way process is performed by the “set()” and “get()” methods respectively, which will throw a default exception if an error occurs when accessing the pertinent cache file. Also, you should notice that the caching class implements a “getInstance()” method, which also returns a Singleton instance of the class. In this way it can be accessed through a single point across the whole framework. At this point, while the previous cache class does a fair job of caching data, it lacks a mandatory feature: it doesn’t implement a method that permits it to determine the validity of a specified cache file. To address that issue, in the section to come I’m going to code that method, thus completing the cache class. To learn how this additional method will be defined, read the next few lines.
blog comments powered by Disqus |
|
|
|
|
|
|
|