<?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);
*/
?>