PHP Cache: Simple File-Based Caching
Ayub Lin September 20, 2012There are times, when you need to serve data that being requested repetitively and the data is not critically needed to be real time, if that’s the case then caching will be a good solution to serve the data faster and more efficient.
Caching works by making the resources can be accessed by less work, it can be achieved by storing what you have processed, so that you could access it easily without repeating the process, the process can be a heavy database query or a remote data access.
There are several ways to store the cache data:
- File
- Database
Or you can use available caching system or framework:
Using a complete caching system is a good decision, they have high performance and robust, but you will need to install them first, there are times where you can’t do this, whether you’re using a limited shared hosting or maybe you just want to use something simple, and maybe you can learn something from implementing simple PHP cache in your own.
And now we will learn about how to implement file-based caching in PHP, the idea is simple we provide a writeable directory for storing the cache files, and we will save processed request on this directory as files, and instead of doing the process again, we will load the data from the cache files. The cache will have expiration time, when the time has reached, the request will be processed again, and the cache will be updated.
Okay, here is the code, implemented as a PHP class, with 2 static function, they are for saving and getting the cached data:
<?php
/**
* Simple file-based chaching mechanism
*/
class Util_Cache
{
public static function save($id, $content)
{
// get cache dir
$conf = Util_Config::load('cache');
$cache_dir = $conf['cache_dir'];
$file = $cache_dir . md5($id);
file_put_contents($file, $content);
}
public static function get($id)
{
// get expiration date
$conf = Util_Config::load('cache');
$exp_time = $conf['exp_time'];
$cache_dir = $conf['cache_dir'];
// check if the file existed
$file = $cache_dir . md5($id);
if( file_exists( $file ) )
{
// check if it's not expired
if( time() - filemtime( $file ) <= $exp_time )
{
// return the content
return file_get_contents($file);
}
else
{
// throw expired
throw new Exception('Cache Expired', 2);
}
}
else
{
// throw not found
throw new Exception('Cache Not Found', 1);
}
}
}
?>
And here is how to use the class:
$data= null;
try {
$data= Util_Cache::get('data');
} catch (Exception $e) {
}
if( ! $data )
{
$data= process_data();
Util_Cache::save('data', $data);
}
The save function, is used to save the data to the cache folder, it require two parameters, they are the unique identifier for the data, and the content of the data that will be cached. And the get function, will return the content of cached data with given identifier.
So that is the simple file-based cache in PHP, it may be simple, but could be really useful.


Comments (1)
you should add a clear method to delete expired entries