I wrote a simple Cache class. It helps you manage file system caching effectively, so use it wisely.
<?php
/**
* Cache Class.
*
* Provides an interface to Cache data to the filesystem.
*
* @author Neo Ighodaro <neo@creativitykills.net>
* @copyright (c) CreativityKills 2013
*/
class Cache {
/**
* Singleton instance of the Cache_Object class.
*
* @var Cache_Object
*/
public static $instance;
/**
* Returns a singleton instance of the Cache_Object class.
*
* @return Cache_Object
*/
public static function instance()
{
if (Cache::$instance === null)
{
// Cache directory
$directory = defined('APP_CACHE_DIRECTORY') ? APP_CACHE_DIRECTORY : dirname(__FILE__);
Cache::$instance = new Cache_Object($directory);
}
return Cache::$instance;
}
/**
* Acts as a facade to magically call methods from the Cache_Object
* class statically.
*
* <code>
* // Save a new cache data
* Cache::put('name', 'Neo', 15);
*
* // Get the saved cache
* Cache::get('name');
*
* // Delete a saved cache
* Cache::forget('name');
*
* // Check if cache has expired
* if (Cache::expired('name'))
* {
* echo 'Cache has expired.';
* }
*
* // Run the caches garbage collector to delete expired cache
* Cache::garbage_collector();
*
* // Manually purge expired cache
* Cache::purge();
* </code>
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public static function __callStatic($method, $parameters)
{
return call_user_func_array(array(Cache::instance(), $method), $parameters);
}
}
class Cache_Object {
/**
* Path to the cache directory with trailing slash. Make sure
* this directory is readable and writable.
*
* @var string
*/
public $cache_directory = '';
/**
* All the cache data.
*
* @var array
*/
public $cache_data = array();
/**
* Initializes the Cache_Object class.
*
* @param string $cache_directory
* @return null
*/
public function __construct($cache_directory)
{
$this->cache_directory = $cache_directory;
}
/**
* Saves a new cache data to the cache directory
*
* @param string $key
* @param mixed $data
* @param integer $lifetime
* @return boolean
*/
public function put($key, $data, $lifetime = 15)
{
// The full path to the cache file
$cache_file = $this->cache_file($key);
// When the cache will expire
$expires_at = time() + ($lifetime*60);
// The full data we want to cache
$this->cache_data[$cache_file] = array(
'data' => $data,
'expires_at' => $expires_at,
);
// Serialize the cache data so we can save it in a text format
$serialized_cache_data = serialize($this->cache_data[$cache_file]);
// Save the cache
file_put_contents($cache_file, $serialized_cache_data);
return $this->has($key);
}
/**
* Get the cached data from a cache file.
*
* @param string $key
* @param mixed $fallback
* @return mixed
*/
public function get($key, $fallback = false)
{
$cache_data = $this->load($key);
if ($cache_data !== false and ! $this->expired($key))
{
return $cache_data['data'];
}
return $fallback;
}
/**
* Check if cache exists in the filesystem.
*
* @param string $key
* @return mixed
*/
public function has($key)
{
return file_exists($this->cache_file($key));
}
/**
* Delete a cache file from the cache directory.
*
* @param string $key
* @return boolean
*/
public function forget($key)
{
if ($cache_data = $this->load($key))
{
$cache_file = $this->cache_file($key);
// Delete the cache file...
unlink($cache_file);
// ...and its spawn ...mwahaha!
unset($this->cache_data[$cache_file]);
return ! $this->has($key);
}
return true;
}
/**
* Load the full data stored in a cache including the expiry time.
*
* @param string $key
* @return array|false
*/
public function load($key)
{
$cache_file = $this->cache_file($key);
if ($this->has($key))
{
if ( ! isset($this->cache_data[$cache_file]))
{
// Get the serialized cache data from the cache file
$serialized_cache_data = file_get_contents($cache_file);
// Unserialize the serialized cache data
$cache_data = unserialize($serialized_cache_data);
$this->cache_data[$cache_file] = $cache_data;
}
return $this->cache_data[$cache_file];
}
return false;
}
/**
* Checks if a cache is expired.
*
* @param string $key
* @return boolean
*/
public function expired($key)
{
if ($cache_data = $this->load($key))
{
return ($cache_data['expires_at'] <= time());
}
return true;
}
/**
* Delete all expired cache files. Use this function sparingly.
*
* @param boolean $full_purge
* @return null
*/
public function purge($full_purge = false)
{
$cache_directory = new DirectoryIterator($this->cache_directory);
foreach ($cache_directory as $file)
{
if ($this->is_cache_file($file->getFilename()))
{
$cache_file = $file->getPathname();
// Full purge mode essentially deletes all the files cached, whether
// they are expired or not.
if ($full_purge === true)
{
unlink($cache_file);
}
// Since this is not a full purge, We'll only delete the cache files
// that are actually marked as expired
else
{
$data = @unserialize(file_get_contents($cache_file));
// We'll check to see if the data stored in this file is valid. If it is
// we'll check the expiry time and delete if its expired.
if (is_array($data) and isset($data['expires_at']))
{
if (time() > $data['expires_at'])
{
unlink($cache_file);
}
}
// This cache file is invalid or corrupt, either way, we dont need
// you to take up unnecessary space...
else
{
unlink($cache_file);
}
}
}
}
}
/**
* Clears expired cache randomly from the cache directory.
* You can call this method everytime a request runs on
* your app to check if purge should be run.
*
* @param integer $probability
* @return string
*/
public function garbage_collector($probability = 5)
{
$lotto_number = rand(0, 100);
if ($probability <= $lotto_number)
{
$this->purge();
}
}
/**
* Get the cache files full path from a specified key.
*
* @param string $key
* @return string
*/
public function cache_file($key)
{
return $this->cache_directory.$this->hash($key).'.cache';
}
/**
* Checks if the given path to a file is a cache file.
*
* @param string $file_path
* @return boolean
*/
protected function is_cache_file($file_path)
{
list($file_name, $extension) = explode('.', $file_path, 2);
return ($extension === 'cache');
}
/**
* Hash a given string.
*
* @param string $string
* @return string
*/
protected function hash($string)
{
return md5($string);
}
}
That is the class. An an example usage is...
<?php
// Load the cache class
require dirname(__FILE__).'/cache.php';
// Set the Cache storage directory
define('APP_CACHE_DIRECTORY', dirname(__FILE__).'/cache/');
function query_cache($sql, $expiry = 15)
{
if ( ! $results = Cache::get($sql))
{
$query = mysql_query($sql);
$results = array();
while ($row = mysql_fetch_array($query))
{
$results[] = $row;
}
Cache::put($sql, $results, $expiry);
}
return $results;
}
// Connect to mysql
$conn = mysql_connect('localhost', 'root', false);
if ($conn)
{
$db = mysql_select_db('test');
}
if ( ! isset($db) or ! $db) die('blah');
// Results are always in array
$results = query_cache("SELECT * FROM rb_user_metas WHERE id = 1");
?><pre><?php var_dump($results); ?></pre>