Here’s a very simple and generic data cache class for Codeigniter:
- since the end of 2008 renames are atomic on both Windows and Linux
- I use the filemtime with the ttl, this means no extra expiry file
- the getter doesn’t return the data, but stores it in a buffer
- values are stored as serialized php files in the CI cache directory
- use it as a plugin: $CI-<load-<plugin(‘SerCache’); //I didn’t want it to behave like a library
Hope someone finds it useful. A more advanced cache for CI may be found here and another one here.
class SerCache {
public $filename;
private $tempfile;
private $ttl;
private $default_ext = '.ser';
public $buffer;
/**
* Simple data cache
* @param string name filename of the cache file (probably an md5 hash)
* @param mixed ttl time to live in seconds; -1 circumvents caching, 'forever' is infinite
*/
public function __construct($name, $ttl = 'forever')
{
$CI =& get_instance();
$path = $CI->config->item('cache_path');
$this->cache_dir = ($path == '') ? BASEPATH.'cache/' : $path;
$this->ttl = $ttl;
if ($ttl == -1)
return FALSE;
$this->filename = $this->cache_dir.$name.$this->default_ext;
$this->tempfile = $name.getmypid();
}
/**
* Fetch data into $this->buffer
* @return bool FALSE if expired or not set, TRUE otherwise
*/
public function get()
{
if ($this->ttl == -1)
return FALSE;
if ($this->ttl == 'forever')
{
if (!file_exists($this->filename))
return FALSE;
}
else
{
if ((!file_exists($this->filename)) OR (filemtime($this->filename) + $this->ttl < time()))
return FALSE;
}
$this->buffer = unserialize(file_get_contents($this->filename));
return TRUE;
}
/**
* Save serialized value to file
* @param mixed value value to be serialized
*/
public function put($value) {
if ($this->ttl == -1)
return FALSE;
file_put_contents($this->tempfile, serialize($value));
rename($this->tempfile, $this->filename);
}
/**
* Deletes the cachefile
*/
public function destroy() {
if (file_exists($this->filename))
{
unlink($this->filename);
}
}
/**
* Returns the filemtime of the cache file
*/
public function filemtime() {
if (file_exists($this->filename))
return filemtime($this->filename);
return 0;
}
}
Example:
$cache = new SerCache('something', $cacheTTL);
if ($cache->get()) {
$var = $cache->buffer;
} else {
//create var here...
$cache->put($var);
}