Skip to content

Instantly share code, notes, and snippets.

@shadowhand
Created December 29, 2008 20:08
Show Gist options
  • Save shadowhand/41367 to your computer and use it in GitHub Desktop.
Save shadowhand/41367 to your computer and use it in GitHub Desktop.
<?php
/**
* Provides simple file-based caching for strings and arrays:
*
* // Set the "foo" cache
* Kohana::cache('foo', 'hello, world');
*
* // Get the "foo" cache
* $foo = Kohana::cache('foo');
*
* All caches are stored as PHP code, generated with [var_export][ref-var].
* Caching objects may not work as expected. Storing references or an
* object or array that has recursion will cause an E_FATAL.
*
* [ref-var]: http://php.net/var_export
*
* @param string name of the cache
* @param mixed data to cache
* @param integer number of seconds the cache is valid for
* @return mixed for getting
* @return boolean for setting
*/
public function cache($name, $data = NULL, $lifetime = 60)
{
// Cache file is a hash of the name
$file = sha1($name).EXT;
// Cache directories are split by keys
$dir = APPPATH.'cache/'.$file[0].'/';
if ($data === NULL)
{
if (is_file($dir.$file))
{
if ((time() - filemtime($dir.$file)) < $lifetime)
{
// Return the cache
return include $dir.$file;
}
else
{
// Cache has expired
unlink($dir.$file);
}
}
// Cache not found
return NULL;
}
if ( ! is_dir($dir))
{
// Create the cache directory
mkdir($dir, 0777);
}
// Serialize the data and create the cache
return (bool) file_put_contents($dir.$file, '<?php return '.var_export($data, TRUE).';');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment