PHP微信開(kāi)發(fā)用Cache 解決數(shù)據(jù)緩存
來(lái)源:易賢網(wǎng) 閱讀:805 次 日期:2016-08-16 14:45:45
溫馨提示:易賢網(wǎng)小編為您整理了“PHP微信開(kāi)發(fā)用Cache 解決數(shù)據(jù)緩存”,方便廣大網(wǎng)友查閱!

用php進(jìn)行微信開(kāi)發(fā)時(shí),碰到access_token長(zhǎng)久保存的問(wèn)題,以前都是用框架里的Cache直接set、get一下就完了。現(xiàn)在沒(méi)框架可用了,只好自己動(dòng)手寫(xiě)一個(gè)cache暫時(shí)用。

這個(gè)Cache類(lèi)用來(lái)緩存一些具有時(shí)效性的數(shù)據(jù),比如微信基礎(chǔ)接口的access_token、網(wǎng)頁(yè)Auth驗(yàn)證的access_token等

下面的代碼使用本地文件進(jìn)行數(shù)據(jù)的緩存

//測(cè)試

 $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); //過(guò)期移除

 return false;

 }

 return $arr["value"];

 }

 public function removeCache($name){

 $this->setCache($name, '', 0);

 }

 private function hasFile(){

 //如果不存在緩存文件,則創(chuàng)建一個(gè)

 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類(lèi)共有set、get、remove三種操作。另外還可以自定義緩存文件的保存路徑,只要設(shè)置Cache的dir屬性就可以了。

以上就是PHP 微信開(kāi)發(fā)時(shí)數(shù)據(jù)緩存的方法,希望對(duì)大家的學(xué)習(xí)有所幫助.

更多信息請(qǐng)查看網(wǎng)絡(luò)編程
易賢網(wǎng)手機(jī)網(wǎng)站地址:PHP微信開(kāi)發(fā)用Cache 解決數(shù)據(jù)緩存
由于各方面情況的不斷調(diào)整與變化,易賢網(wǎng)提供的所有考試信息和咨詢(xún)回復(fù)僅供參考,敬請(qǐng)考生以權(quán)威部門(mén)公布的正式信息和咨詢(xún)?yōu)闇?zhǔn)!
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡(jiǎn)要咨詢(xún) | 簡(jiǎn)要咨詢(xún)須知 | 加入群交流 | 手機(jī)站點(diǎn) | 投訴建議
工業(yè)和信息化部備案號(hào):滇ICP備2023014141號(hào)-1 云南省教育廳備案號(hào):云教ICP備0901021 滇公網(wǎng)安備53010202001879號(hào) 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號(hào)
云南網(wǎng)警備案專(zhuān)用圖標(biāo)
聯(lián)系電話(huà):0871-65317125(9:00—18:00) 獲取招聘考試信息及咨詢(xún)關(guān)注公眾號(hào):hfpxwx
咨詢(xún)QQ:526150442(9:00—18:00)版權(quán)所有:易賢網(wǎng)
云南網(wǎng)警報(bào)警專(zhuān)用圖標(biāo)