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屬性就可以了。
?
轉載于:https://www.cnblogs.com/lhat/p/5527033.html
總結
- 上一篇: 关于JSON的简介及取值以及常见面试题
- 下一篇: IIs+php 最精简的环境配置