這篇文章主要講解了“PHP進(jìn)行微信開發(fā)如何解決數(shù)據(jù)緩存問題”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“PHP進(jìn)行微信開發(fā)如何解決數(shù)據(jù)緩存問題”吧!
用php進(jìn)行微信開發(fā)時,碰到access_token長久保存的問題,以前都是用框架里的Cache直接set、get一下就完了?,F(xiàn)在沒框架可用了,只好自己動手寫一個cache暫時用。
這個Cache類用來緩存一些具有時效性的數(shù)據(jù),比如微信基礎(chǔ)接口的access_token、網(wǎng)頁Auth驗證的access_token等
下面的代碼使用本地文件進(jìn)行數(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 = "./cach3/"; //目錄 //緩存 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三種操作。另外還可以自定義緩存文件的保存路徑,只要設(shè)置Cache的dir屬性就可以了。
感謝各位的閱讀,以上就是“PHP進(jìn)行微信開發(fā)如何解決數(shù)據(jù)緩存問題”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對PHP進(jìn)行微信開發(fā)如何解決數(shù)據(jù)緩存問題這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是創(chuàng)新互聯(lián)網(wǎng)站建設(shè)公司,,小編將為大家推送更多相關(guān)知識點(diǎn)的文章,歡迎關(guān)注!
網(wǎng)站題目:PHP進(jìn)行微信開發(fā)如何解決數(shù)據(jù)緩存問題-創(chuàng)新互聯(lián)
網(wǎng)站路徑:http://chinadenli.net/article28/deiicp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計、面包屑導(dǎo)航、Google、標(biāo)簽優(yōu)化、App設(shè)計、自適應(yīng)網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容