標籤:
儲存靜態緩衝即把緩衝寫入檔案。
file.php
<?phpclass Cache{ //靜態快取檔案尾碼名 const EXT = ‘txt‘; //定義快取檔案存放路徑 private $_dir; public function __construct(){ $this->_dir = dirname(__FILE__).‘/files/‘; } public function cacheData($k,$v = ‘‘,$path = ‘‘){ //檔案名稱 $filename = $this->_dir.$path.$k.‘.‘.self::EXT; //$v不為‘’:儲存緩衝或者刪除緩衝 if($v !== ‘‘){ //刪除緩衝 if(is_null($v)){ return @unlink($filename); } //儲存緩衝 $dir = dirname($filename); if(!is_dir($dir)){ mkdir($dir,0777); } //把$v轉成string類型 return file_put_contents($filename,json_encode($v)); } //讀取緩衝 if(!is_file($filename)){ return false; }else{ return json_decode(file_get_contents($filename),true); } }}
testfile.php
<?phprequire ‘file.php‘;$data = array( ‘id‘=>1, ‘name‘=>‘Mary‘, ‘type‘=>array(1,3,6));$file_cache = new Cache();//儲存緩衝if($file_cache->cacheData(‘index_cache‘,$data)){ echo ‘success‘;}else{ echo ‘error‘;}//讀取緩衝if($con = $file_cache->cacheData(‘index_cache‘)){ var_dump($con);}else{ echo ‘error‘;}//刪除緩衝if($con = $file_cache->cacheData(‘index_cache‘,null)){ echo ‘delete success‘;}else{ echo ‘error‘;}
======
稍微修改一下,設定n分鐘的緩衝,超過n分鐘則重建緩衝,否則從緩衝中讀取資料。
在file.php 中,儲存資料時把檔案名稱和檔案修改時間也同時存入快取資料
<?phpclass Cache{ //靜態快取檔案尾碼名 const EXT = ‘txt‘; //定義快取檔案存放路徑 private $_dir; public function __construct(){ $this->_dir = dirname(__FILE__).‘/files/‘; } public function cacheData($k,$v = ‘‘,$path = ‘‘){ //檔案名稱 $filename = $this->_dir.$path.$k.‘.‘.self::EXT; //$v不為‘’:儲存緩衝或者刪除緩衝 if($v !== ‘‘){ //刪除緩衝 if(is_null($v)){ return @unlink($filename); } //儲存緩衝 $dir = dirname($filename); if(!is_dir($dir)){ mkdir($dir,0777); } //把$v轉成string類型 $_return = array( ‘filename‘ => $filename, ‘filetime‘ => @filemtime($filename), //檔案建立(修改)時間 ‘con‘ => json_encode($v) ); return file_put_contents($filename,json_encode($_return)); } //讀取緩衝 if(!is_file($filename)){ return false; }else{ return json_decode(file_get_contents($filename),true); } }}
testfile.php
<?phprequire ‘file.php‘;$data = array( ‘id‘=>1, ‘name‘=>‘Mary‘, ‘type‘=>array(1,3,6));$file_cache = new Cache();//設定5min的緩衝,超過30s則重建緩衝,否則從緩衝中讀取資料$k = ‘index_cache‘;$countdown = 5*60;$con = $file_cache->cacheData($k);if($con){ //如果能夠讀取緩衝 if(time()-$con[‘filetime‘] > 30){ $file_cache->cacheData($k,$data); var_dump($data); }else{ $res = $file_cache->cacheData($k); if($res){ var_dump(json_decode($res[‘con‘],true)); } }}else{ //如果緩衝不存在則建立緩衝 $file_cache->cacheData($k,$data); var_dump($data);}
PHP 開發 APP 介面總結 - 靜態緩衝