PHP緩衝之檔案快取,

來源:互聯網
上載者:User

PHP緩衝之檔案快取,
1、PHP檔案快取內容儲存格式
       PHP檔案快取內容儲存格式主要有三種:
       (1)變數 var_export 格式化成PHP正常的賦值書寫格式;
       (2)變數 serialize 序列化之後儲存,用的時候還原序列化;
       (3)變數 json_encode格式化之後儲存,用的時候json_decode
       互連網上測試結果是:serialize格式的檔案解析效率大於Json,Json的解析效率大於PHP正常賦值。
       所以我們要是快取資料建議採用序列化的形式解析資料會更快。

2、PHP檔案快取的簡單案例

<?phpclass Cache_Driver{//定義緩衝的路徑protected $_cache_path;//根據$config中的cache_path值擷取路徑資訊public function Cache_Driver($config){if(is_array($config) && isset($config['cache_path'])){   $this->_cache_path = $config['cache_path'];}else{   $this->_cache_path = realpath(dirname(__FILE__)."/")."/cache/";}}//判斷key值對應的檔案是否存在,如果存在,讀取value值,value以序列化儲存public function get($id){if ( ! file_exists($this->_cache_path.$id)){return FALSE;}$data = @file_get_contents($this->_cache_path.$id);$data = unserialize($data);if(!is_array($data) || !isset($data['time']) || !isset($data['ttl'])){return FALSE;}if ($data['ttl'] > 0 && time() >  $data['time'] + $data['ttl']){@unlink($this->_cache_path.$id);return FALSE;}return $data['data'];}//設定緩衝資訊,根據key值,產生相應的快取檔案public function set($id, $data, $ttl = 60){$contents = array('time'=> time(),'ttl'=> $ttl,'data'=> $data);if (@file_put_contents($this->_cache_path.$id, serialize($contents))){@chmod($this->_cache_path.$id, 0777);return TRUE;}return FALSE;}//根據key值,刪除快取檔案public function delete($id){return @unlink($this->_cache_path.$id);}public function clean(){      $dh = @opendir($this->_cache_path);   if(!$dh)         return FALSE;            while ($file = @readdir($dh))      {         if($file == "." || $file == "..")            continue;                  $path = $this->_cache_path."/".$file;         if(is_file($path))            @unlink($path);      }      @closedir($dh);      return TRUE;}}





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.