There are many types of caching mechanisms like memcached, APC, eAccelerator but for the simplicity of this tip, we will use plain file to hold our cache data. This is enough in most of cases.
<?php
/**
* @desc Class that implements the Cache functionality
*/
class Cache
{
/**
* Function read retrieves value from cache
*
* @param $fileName -
* name of the cache file
* Usage: Cache::read('fileName.extension')
*/
function read ($fileName)
{
$fileName = '/path/to/cache/folder' . $fileName;
if (file_exists($fileName)) {
$handle = fopen($fileName, 'rb');
$variable = fread($handle, filesize($fileName));
fclose($handle);
return unserialize($variable);
} else {
return null;
}
}
/**
* Function for writing key => value to cache
*
* @param $fileName -
* name of the cache file (key)
* @param $variable -
* value
* Usage: Cache::write('fileName.extension', value)
*/
function write ($fileName, $variable)
{
$fileName = '/path/to/cache/folder' . $fileName;
$handle = fopen($fileName, 'a');
fwrite($handle, serialize($variable));
fclose($handle);
}
/**
* Function for deleteing cache file
*
* @param $fileName -
* name of the cache file (key)
* Usage: Cache::delete('fileName.extension')
*/
function delete ($fileName)
{
$fileName = '/path/to/cache/folder' . $fileName;
@unlink($fileName);
}
}
//
// :: Save above code as `cache.php`
//
//
// :: Here is how you can use this in your application
//
require_once ('cache.php');
// instantiate it
$cache = new Cache();
// let's check if some cache file exists
$data = $cache->read('test_17.tmp'); // 17 is id of the article, for example
// it doesn't exist, fetch data from database
if (empty($data)) {
$sql = "SELECT image, user_id, content FROM table WHERE id = 17";
$data = $db->select_list($sql); // just an example
$cache->write('test_17.tmp', $data);
}
// then use the data as you would normally
foreach ($data as $row) {
//
}
//
// This way you will gain some speed and your database server will thank you.
//
// But there is a catch! It is very, very important not to forget to clear
// this cache if something gets changed on that particular article.
// So do not forget to add this lines after your update the article:
//
// include the class
require_once ('cache.php');
// instantiate it
$cache = new Cache();
// updating the article example
$data = 'some array for updating';
$db->update_record('table', $data);
// delete the cached item
$cache->delete('test_17.tmp');
?>