php数据缓存

用php进行微信开发时,碰到access_token长久保存的问题,以前都是用框架里的Cache直接set、get一下就完了。现在没框架可用了,只好自己动手写一个cache暂时用。

这个Cache类用来缓存一些具有时效性的数据,比如微信基础接口的access_token、网页Auth验证的access_token等

下面的代码使用本地文件进行数据的缓存

 

 1 //测试
 2 $cache = new Cache();
 3 $cache->dir = "../cc/";
 4 //$cache->setCache("zhang", "zhangsan", 100);
 5 echo $cache->getCache("zhang");
 6 //$cache->removeCache("zhang");
 7 
 8 $cache->setCache("liu", "liuqi", 100);
 9 echo $cache->getCache("liu");
10 
11 class Cache{
12     public $cacheFile = "cache.json";    //文件
13     public $dir = "./cach2/";            //目录
14 
15     //缓存
16     public function setCache($name, $val, $expires_time){
17         $file = $this->hasFile();
18         //字符串转数组
19         $str = file_get_contents($file);
20         $arr = json_decode($str, true);
21         
22         //值为空,则移除该缓存
23         if(empty($val)){
24             unset($arr[$name]);
25         }else{
26             $arr[$name] = array("value"=>$val, "expires_time"=>$expires_time, "add_time"=>time());
27         }    
28         //数组转字符串
29         $str = json_encode($arr);
30         file_put_contents($file, $str);
31     }
32     public function getCache($name){
33         $file = $this->hasFile();
34         
35         //字符串转数组
36         $str = file_get_contents($file);
37         $allArr = json_decode($str, true);
38         $arr = $allArr[$name];
39 
40         if(!$arr || time() > ($arr["expires_time"] + $arr["add_time"])){
41             $this->removeCache($name);    //过期移除
42             return false;
43         }
44         return $arr["value"];
45     }
46     public function removeCache($name){
47         $this->setCache($name, '', 0);
48     }
49     
50     private function hasFile(){
51         //如果不存在缓存文件,则创建一个
52         if(!file_exists($this->dir)){
53             mkdir($this->dir);
54         }
55         if(!file_exists($this->dir . $this->cacheFile)){
56             touch($this->dir . $this->cacheFile);
57         }
58         return $this->dir . $this->cacheFile;
59     }
60 }

上面的Cache类共有set、get、remove三种操作。另外还可以自定义缓存文件的保存路径,只要设置Cache的dir属性就可以了。

 

posted @ 2016-05-25 14:58  刘一二  阅读(650)  评论(0编辑  收藏  举报