国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > PHP > 正文

PHP微信開發用Cache 解決數據緩存

2024-05-04 23:47:47
字體:
來源:轉載
供稿:網友

用php進行微信開發時,碰到access_token長久保存的問題,以前都是用框架里的Cache直接set、get一下就完了?,F在沒框架可用了,只好自己動手寫一個cache暫時用。

這個Cache類用來緩存一些具有時效性的數據,比如微信基礎接口的access_token、網頁Auth驗證的access_token等

下面的代碼使用本地文件進行數據的緩存,

//測試 $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(); //字符串轉數組 $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()); }  //數組轉字符串 $str = json_encode($arr); file_put_contents($file, $str); } public function getCache($name){ $file = $this->hasFile();  //字符串轉數組 $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(){ //如果不存在緩存文件,則創建一個 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 微信開發時數據緩存的方法,希望對大家的學習有所幫助.


注:相關教程知識閱讀請移步到PHP教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 海淀区| 昂仁县| 丹凤县| 榆树市| 视频| 怀安县| 浦东新区| 惠安县| 紫云| 云梦县| 鄂伦春自治旗| 清镇市| 浦江县| 麻栗坡县| 沈丘县| 屏东县| 朔州市| 喜德县| 洛浦县| 稷山县| 乌拉特后旗| 东丰县| 本溪市| 大港区| 通州区| 德庆县| 东阳市| 平塘县| 剑川县| 新泰市| 河东区| 望奎县| 乌苏市| 衡山县| 宣威市| 西充县| 韶山市| 龙井市| 闽侯县| 任丘市| 本溪|