PHP微信開發(fā)用Cache 解決數(shù)據(jù)緩存
用php進行微信開發(fā)時,碰到access_token長久保存的問題,以前都是用框架里的Cache直接set、get一下就完了?,F(xiàn)在沒框架可用了,只好自己動手寫一個cache暫時用。
這個Cache類用來緩存一些具有時效性的數(shù)據(jù),比如微信基礎接口的access_token、網(wǎng)頁Auth驗證的access_token等
下面的代碼使用本地文件進行數(shù)據(jù)的緩存,
//測試 $cache = new Cache(); $cache->dir = "../cc/"; //$cache->setCache("zhang", "zhangsan", 100); echo $cache->getCache("zhang"); //$cache->removeCache("zhang"); $cache->setCache("liu", "liuqi", 100); echo $cache->getCache("liu"); class Cache{ public $cacheFile = "cache.json"; //文件 public $dir = "./cach2/"; //目錄 //緩存 public function setCache($name, $val, $expires_time){ $file = $this->hasFile(); //字符串轉(zhuǎn)數(shù)組 $str = file_get_contents($file); $arr = json_decode($str, true); //值為空,則移除該緩存 if(empty($val)){ unset($arr[$name]); }else{ $arr[$name] = array("value"=>$val, "expires_time"=>$expires_time, "add_time"=>time()); } //數(shù)組轉(zhuǎn)字符串 $str = json_encode($arr); file_put_contents($file, $str); } public function getCache($name){ $file = $this->hasFile(); //字符串轉(zhuǎn)數(shù)組 $allArr = json_decode($str, true); $arr = $allArr[$name]; if(!$arr || time() > ($arr["expires_time"] + $arr["add_time"])){ $this->removeCache($name); //過期移除 return false; } return $arr["value"]; } public function removeCache($name){ $this->setCache($name, '', 0); } private function hasFile(){ //如果不存在緩存文件,則創(chuàng)建一個 if(!file_exists($this->dir)){ mkdir($this->dir); } if(!file_exists($this->dir . $this->cacheFile)){ touch($this->dir . $this->cacheFile); } return $this->dir . $this->cacheFile; } }
上面的Cache類共有set、get、remove三種操作。另外還可以自定義緩存文件的保存路徑,只要設置Cache的dir屬性就可以了。
以上就是PHP 微信開發(fā)時數(shù)據(jù)緩存的方法,希望對大家的學習有所幫助.
相關文章
PHP實現(xiàn)將多個文件中的內(nèi)容合并為新文件的方法示例
這篇文章主要介紹了PHP實現(xiàn)將多個文件中的內(nèi)容合并為新文件的方法,涉及php編碼轉(zhuǎn)換、文件與目錄的遍歷以及文件讀寫相關操作技巧,需要的朋友可以參考下2017-06-06支持php4、php5的mysql數(shù)據(jù)庫操作類
2008-01-01Linux環(huán)境下php實現(xiàn)給網(wǎng)站截圖的方法
這篇文章主要介紹了Linux環(huán)境下php實現(xiàn)給網(wǎng)站截圖的方法,結(jié)合實例形式較為詳細的分析了Linux環(huán)境下php實現(xiàn)網(wǎng)站截圖的具體步驟與相關操作技巧,需要的朋友可以參考下2016-05-05PHP創(chuàng)建文件,并向文件中寫入數(shù)據(jù),覆蓋,追加的實現(xiàn)代碼
這篇文章主要介紹了PHP創(chuàng)建文件,并向文件中寫入數(shù)據(jù),覆蓋,追加的實現(xiàn)代碼,需要的朋友可以參考下2016-03-03php實現(xiàn)word轉(zhuǎn)html的方法
這篇文章主要介紹了php實現(xiàn)word轉(zhuǎn)html的方法,涉及PHP調(diào)用com組件操作word文檔的相關技巧,需要的朋友可以參考下2016-01-01