As usual, before I begin adding to the framework, I'm going to reintroduce the definition of the cache class created in the previous tutorial, in case you haven’t read the article yet. It's a breeze to understand how this caching class functions. If you’re not convinced of this, take a look at the following code fragment. It's the file containing the class in question. Here it is: (Cache.php) <?php 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); }
// check if the cache file is valid or not public function valid($id) { $file = glob($this->cachedir . $id); $file = array_shift($file); return (bool)(time() - filemtime($file) <= $this->expire); } }// End Cache class By looking closely at the above cache class, it’s clear to see that its workhorse methods are “set()” and “get().” These methods permit you to write data to a specified cache file and retrieve that data from the file. Apart from these, there’s an additional method called “valid(),” which allows you to determine if the cached data is valid or not through a time-based caching strategy. Having outlined how this basic cache class does its thing, I'm going to create a new class that parses view files in a simple manner. To see how this will be done, click on the link that appears below and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|