Created
December 29, 2008 20:08
-
-
Save shadowhand/41367 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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