When writing more advanced PHP based online applications the need to improve performance is often desirable. By caching arrays of data that have been queried from a database such as MYSQL you can save substantial CPU cycles, particularly with data that is needed frequently but seldom changes.
Instead of querying the database each time a page is called, we can read the file contents and have the data at our fingertips. For simple queries this will only be necessary in high traffic websites but in more complicated queries using full text index and multiple table joins, caching data can drastically reduce load with even a medium volume of traffic.
Below is a PHP data caching class I wrote that caches variables using file handle read and write to cache data with or without an expiration time. I used file_get_contents() rather than fread to speed up the application even further. Rather than run a query each time the data is needed, the default is to cache it for 3600 seconds or an hour.
Configurations you may wish to change:
You can download the ObjectCache.class.php PHP5 cache here.
<?php /** * Caches manipulated variables into files for future use * @author Charles Weiss < c w e i s s [ a t ] f t w m a r k e t i n g . c o m > * @copyright Copyright (C) Fetch The Web 2006-2008 * @version 0.1 */ class ObjectCache { private $data; private $ext = '_ObjectCache.php'; // The group of the cache file ( appended to end of filename ) private $path = '/tmp/'; // The FULL path to the cached file function __construct() { $this->data = array(); } /** * Fetches variable from the cache if cache exists and data has not expired * @param $id The id of that variable for use in the filename * @param $lock Optional parameter instructing the class to lock the file. * @return the cache contents OR false on error */ function get($id) { if (isset($this->data[$id])) return $this->data[$id]; // Already set, return to sender $path = $this->path.base64_encode($id).$this->ext; if (file_exists($path) && is_readable($path)) { // Check if the cache file exists include $path; if (isset($expires) && $expires <= time()) { $this->clear($id); return false; } else { $cache = file_get_contents($path); } } else { return false; } } /** * Sets variable into the cache * @param $id The id of that variable for use in the filename * @param $cache The data to be stored * @param $lifetime The expiration time (in seconds) from file creation * @return the cache contents OR false on error */ function put($id, $cache, $lifetime = 0) { $this->data[$id] = $cache; if (is_resource($cache)) return "Can't cache resource."; $path = $this->path.base64_encode($id).$this->ext; $fp = @fopen($path, 'w'); if (!$fp) echo 'Unable to open file for writing.'.$path; @flock($fp, LOCK_EX); @fwrite($fp, '<?php $cache='.var_export($data, true).';'); if ($lifetime > 0) @fwrite($fp, '$expires='.(time()+$lifetime).';'); @fwrite($fp, ' ?>'); @flock($fp, LOCK_UN); @fclose($fp); if (file_exists($path)) chmod($path, 666); else return false; return true; } /** * Deletes the cache file * @param $id The id of that variable for use in the filename * @param $lock Optional parameter instructing the class to lock the file. * @return the true or descriptive string on error */ function clear($id) { if (isset($this->data[$id])) unset($this->data[$id]); $pretty_id = base64_encode($id); $path = $this->path.$pretty_id.$this->ext; if (file_exists($path) && unlink($path)) return true; else return 'Cache could not be cleared.'; } } ?> |
Example usage:
include './ObjectCache.class.php'; $data = array('a','b','c','d','e','f','g'); $distinct_name = 'lala'; $cache = new ObjectCache(); // Cache will last 3600 seconds or 1 hr $cache->put($distinct_name, $data, 3600); $data2 = $cache->get($distinct_name); // Forcibly clear the cache (on data update via admin perhaps //$cache->clear($distinct_name); print_r($data2); unset($cache); |
I would like to have run this example live but unfortunately the server this site is hosted on is php4 at the moment so you will have to run it on your own box.
Hope this helps some of you. Feel free to give credit or not; whatever makes your socks go up and down! ![]()
July 4th, 2008 at 4:30 am
Font of your code is very small almost unreadable. I have tried by clicking in “View code” but in vain.
November 8th, 2008 at 9:38 am
Hi, your code has a lot of errors and doesn’t work “out-of-the-box”. If you don’t mind I’ll post a fixed version on my blog.