本文執行個體講述了PHP檔案快取內容儲存格式,對於進行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; }}
希望本文所述PHP緩衝執行個體對大家的PHP程式開發能起到一定的協助借鑒作用。