1 //文件缓存类
2
3 class FileCache {
4 private $cacheTime = 3600; //默认缓存时间 秒
5 private $cacheDir = './filecache'; //缓存绝对路径
6 private $md5 = true; //是否对键进行加密
7 private $suffix = ".php"; //设置文件后缀
8
9 public function __construct($config){
10 if( is_array( $config ) ){
11 foreach( $config as $key=>$val ){
12 $this->$key = $val;
13 }
14 }
15 }
16
17 //设置缓存
18 public function set($key,$val,$leftTime=null){
19 $key = $this->md5 ? md5($key) : $key;
20 $leftTime = $leftTime ? $leftTime : $this->cacheTime;
21 !file_exists($this->cacheDir) && mkdir($this->cacheDir,0777);
22 $file = $this->cacheDir.'/'.$key.$this->suffix;
23 $val = serialize($val);
24 @file_put_contents($file,$val) or $this->error(__line__,"文件写入失败");
25 @chmod($file,0777) or $this->error(__line__,"设定文件权限失败");
26 @touch($file,time()+$leftTime) or $this->error(__line__,"更改文件时间失败");
27 }
28
29 //得到缓存
30 public function get($key){
31 $this->clear();
32 if( $this->_isset($key) ){
33 $key_md5 = $this->md5 ? md5($key) : $key;
34 $file = $this->cacheDir.'/'.$key_md5.$this->suffix;
35 $val = file_get_contents($file);
36 return unserialize($val);
37 }
38 return null;
39 }
40
41 //判断文件是否有效
42 public function _isset($key){
43 $key = $this->md5 ? md5($key) : $key;
44 $file = $this->cacheDir.'/'.$key.$this->suffix;
45 if( file_exists($file) ){
46 if( @filemtime($file) >= time() ){
47 return true;
48 }else{
49 @unlink($file);
50 return false;
51 }
52 }
53 return false;
54 }
55
56 //删除文件
57 public function _unset($key){
58 if( $this->_isset($key) ){
59 $key_md5 = $this->md5 ? md5($key) : $key;
60 $file = $this->cacheDir.'/'.$key_md5.$this->suffix;
61 return @unlink($file);
62 }
63 return false;
64 }
65
66 //清除过期缓存文件
67 public function clear(){
68 $files = scandir($this->cacheDir);
69 foreach ($files as $val){
70 if (@filemtime($this->cacheDir."/".$val) < time()){
71 @unlink($this->cacheDir."/".$val);
72 }
73 }
74 }
75
76 //清除所有缓存文件
77 public function clear_all(){
78 $files = scandir($this->cacheDir);
79 foreach ($files as $val){
80 @unlink($this->cacheDir."/".$val);
81 }
82 }
83
84 private function error($line,$msg){
85 die("出错文件:".__file__."/n出错行:$line/n错误信息:$msg");
86 }
调用方法:
//cacheTime 缓存时间 1个小时
$cacheFile = new FileCache(array('cacheTime'=>3600,'suffix'=>'.php'));
$cache_1 =$cacheFile->get('key1');
$cache_2 =$cacheFile->get('key2');
if( $cache_1 ){
$resArr_result = $cache_1;
}else{
//读数据库$resArr_result = array(***);
//设置缓存
$cacheFile->set('key1',$resArr_result);
}