PHP微信開發用Cache 解決資料緩衝_php技巧

來源:互聯網
上載者:User

用php進行微信開發時,碰到access_token長久儲存的問題,以前都是用架構裡的Cache直接set、get一下就完了。現在沒架構可用了,只好自己動手寫一個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 微信開發時資料緩衝的方法,希望對大家的學習有所協助.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.