class cache {
public function __construct() {
if (!defined('CACHE_PATH'))
define('CACHE_PATH', __SITE_PATH . '/caches');
}
}
Note: You must create cache directory before.
The __construct() define CACHE_PATH if it is't defined.
To save cache , we create two file that have extenstion is .cache, .info.
it is easy to remember , you can change to another extension name if you want.Below is save cache function
public function save($id, $time, $content) {
if (!__ENABLE_CACHE)
return;
$file_info = CACHE_PATH . "/$id.info";
$file_cache = CACHE_PATH . "/$id.cache";
//Equal current time add the long time
$time = time() + ($time * 60);
$handle = fopen($file_info, 'w+');
if(!fwrite($handle, $time))
return false;
fclose($handle);
$content =serialize($content);
$handle = fopen($file_cache, 'w+');
if(!fwrite($handle, $content))
return false;
fclose($handle);
}
the input parameter is
- $id to indentify the id cache.
- $time is the long life is calculated by minutes.
- $content is object that you want to cache.
The check it we have below function:
public function isValid($id)
{
$file_info = CACHE_PATH . "/$id.info";
if (!file_exists($file_info))
return false;
$file_time =file_get_contents($file_info);
return (time() < $file_time);
}
And this is finally function, get object from cache file.
public function getCache($id)
{
$file_cache = CACHE_PATH . "/$id.cache";
if (!file_exists($file_cache))
die("File $file_cache not found");
$content = file_get_contents($file_cache);
return unserialize($content);
}
And this is full code
class cache {
public function __construct() {
if (!defined('CACHE_PATH'))
define('CACHE_PATH', __SITE_PATH . '/caches');
}
/*
* $id is the key to save cache
* $time is calculated by minutes
* $content is the content will be cached.
*/
public function getCache($id)
{
$file_cache = CACHE_PATH . "/$id.cache";
if (!file_exists($file_cache))
die("File $file_cache not found");
$content = file_get_contents($file_cache);
return unserialize($content);
}
public function save($id, $time, $content) {
if (!__ENABLE_CACHE)
return;
$file_info = CACHE_PATH . "/$id.info";
$file_cache = CACHE_PATH . "/$id.cache";
//Equal current time add the long time
$time = time() + ($time * 60);
$handle = fopen($file_info, 'w+');
if(!fwrite($handle, $time))
return false;
fclose($handle);
$content =serialize($content);
$handle = fopen($file_cache, 'w+');
if(!fwrite($handle, $content))
return false;
fclose($handle);
}
public function isValid($id)
{
$file_info = CACHE_PATH . "/$id.info";
if (!file_exists($file_info))
return false;
$file_time =file_get_contents($file_info);
return (time() < $file_time);
}
}