PHP缓存类简介与基础配置
尽管网络上关于 PHP 缓存类的教程和资料层出不穷,但这款被发现的缓存类在确保功能覆盖实际需求的同时,保持了令人惊叹的简洁性。无需多言,直接展示其核心代码及使用方式。 使用说明如下: 1、实例化对象 $cache = new Cache(); 2、配置缓存时长与存储路径 $cache = new Cache(60, '/any_other_path/'); 构造函数的第一个参数用于设定缓存有效期(单位:秒),第二个参数指定缓存文件的存放目录,用户可根据实际项目需求进行调整。 若未传入参数,系统将采用默认配置:缓存有效期为 3600 秒,存储目录默认为 cache/ 3、获取缓存内容 $value = $cache->get('data_key'); 4、存入缓存数据 $value = $cache->put('data_key', 'data_value'); 以下是完整的调用实例:
$cache = new Cache();
//从缓存从读取键值 $key 的数据
$values = $cache->get($key);
//如果没有缓存数据
if ($values == false) {
//insert code here...
//写入键值 $key 的数据
$cache->put($key, $values);
} else {
//insert code here...
}
Cache.class.php
<?php
class Cache {
private $cache_path;//path for the cache
private $cache_expire;//seconds that the cache expires
//cache constructor, optional expiring time and cache path
public function Cache($exp_time=3600,$path="cache/"){
$this->cache_expire=$exp_time;
$this->cache_path=$path;
}
//returns the filename for the cache
private function fileName($key){
return $this->cache_path.md5($key);
}
//creates new cache files with the given data, $key== name of the cache, data the info/values to store
public function put($key, $data){
$values = serialize($data);
$filename = $this->fileName($key);
$file = fopen($filename, 'w');
if ($file){//able to create the file
fwrite($file, $values);
fclose($file);
}
else return false;
}
//returns cache for the given key
public function get($key){
$filename = $this->fileName($key);
if (!file_exists($filename) || !is_readable($filename)){//can't read the cache
return false;
}
if ( time() < (filemtime($filename) + $this->cache_expire) ) {//cache for the key not expired
$file = fopen($filename, "r");// read data file
if ($file){//able to open the file
$data = fread($file, filesize($filename));
fclose($file);
return unserialize($data);//return the values
}
else return false;
}
else return false;//was expired you need to create new
}
}
?>
相信这款设计精巧、代码简练的 PHP 缓存类能为您带来便利,希望上述内容能对您的开发学习提供切实帮助。