diff --git a/src/Pluf/Cache.php b/src/Pluf/Cache.php new file mode 100644 index 0000000..ee45b8a --- /dev/null +++ b/src/Pluf/Cache.php @@ -0,0 +1,72 @@ + + * $cache = new Pluf_Cache_File(); + * if (null === ($foo=$cache->get('my-key'))) { + * $foo = run_complex_operation(); + * $cache->set('my-key', $foo); + * } + * return $foo; + * + * + * The value to be stored in the cache must be serializable. + * + * @see http://www.php.net/serialize + */ +class Pluf_Cache +{ + /** + * Set a value in the cache. + * + * @param string Key to store the information + * @param mixed Value to store + * @param int Timeout in seconds (null) + * @return bool Success + */ + public function set($key, $value, $timeout=null) + { + throw new Pluf_Exception_NotImplemented(); + } + + /** + * Get value from the cache. + * + * @param string Key to get the information + * @param mixed Default value to return if cache miss (null) + * @param mixed Stored value or default + */ + public function get($key, $default=null) + { + throw new Pluf_Exception_NotImplemented(); + } +} diff --git a/src/Pluf/Cache/File.php b/src/Pluf/Cache/File.php new file mode 100644 index 0000000..28e4da1 --- /dev/null +++ b/src/Pluf/Cache/File.php @@ -0,0 +1,88 @@ +_keyToFile($key); + $dir = dirname($fname); + if ($timeout == null) $timeout = Pluf::f('cache_timeout', 300); + if (!file_exists($dir)) mkdir($dir, 0777, true); + $expire = time()+$timeout; + file_put_contents($fname, $expire."\n".serialize($value)); + } + + /** + * Get value from the cache. + * + * @param string Key to get the information + * @param mixed Default value to return if cache miss (null) + * @param mixed Stored value or default + */ + public function get($key, $default=null) + { + $fname = $this->_keyToFile($key); + if (!file_exists($fname)) return $default; + list($timeout, $content) = explode("\n", file_get_contents($fname), 2); + if ($timeout < time()) { + unlink($fname); + return $default; + } + return unserialize($content); + } + + /** + * Convert a key into a path to a file. + * + * @param string Key + * @return string Path to file + */ + public function _keyToFile($key) + { + $md5 = md5($key); + return Pluf::f('cache_file_folder').'/'.substr($md5, 0, 2) + .'/'.substr($md5, 2, 2).'/'.substr($md5, 4); + } +}