| 本文分享一個php檔案快取資料類,寫的挺規範挺好的,後面有調用樣本。有需要的朋友參考下。 說到php檔案快取,回顧之前介紹的文章,找到了這麼幾篇:php 緩衝類 調用樣本 PHP 資料緩衝的執行個體代碼 php 頁面緩衝類,大家可以參考下。有了以上對於php 檔案快取的基礎,下面開始今天的內容。代碼如下: cachePath = $path; } } /** * 解構函式 */ function __destruct() { //nothing } /** * 在cache中設定鍵為$key的項的值,如果該項不存在,則建立一個項 * @param string $key 索引值 * @param mix $var 值 * @param int $expire 到期秒數 * @param int $flag 標誌位 * @return bool 如果成功則返回 TRUE,失敗則返回 FALSE。 * @access public */ public function set($key, $var, $expire = 36000, $flag = 0) { $value = serialize($var); $timeout = time() + $expire; $result = safe_file_put_contents($this->cachePath . urlencode($key) .'.cache', $timeout . '<<%-==-%>>' . $value); return $result; } /** * 在cache中擷取鍵為$key的項的值 * @param string $key 索引值 * @return string 如果該項不存在,則返回false * @access public */ public function get($key) { $file = $this->cachePath . urlencode($key) .'.cache'; if (file_exists($file)) { $content = safe_file_get_contents($file); if ($content===false) { return false; } $tmp = explode('<<%-==-%>>', $content); $timeout = $tmp[0]; $value = $tmp[1]; if (time()>$timeout) { $result = false; } else { $result = unserialize($value); } } else { $result = false; } return $result; } /** * 清空cache中所有項 * @return 如果成功則返回 TRUE,失敗則返回 FALSE。 * @access public */ public function flush() { $fileList = FileSystem::ls($this->cachePath,array(),'asc',true); return FileSystem::rm($fileList); } /** * 刪除在cache中鍵為$key的項的值 * @param string $key 索引值 * @return 如果成功則返回 TRUE,失敗則返回 FALSE。 * @access public */ public function delete($key) { return FileSystem::rm($this->cachePath . $key .'.cache'); } } if (!function_exists('safe_file_put_contents')) { function safe_file_put_contents($filename, $content) { $fp = fopen($filename, 'wb'); if ($fp) { flock($fp, LOCK_EX); fwrite($fp, $content); flock($fp, LOCK_UN); fclose($fp); return true; } else { return false; } } } if (!function_exists('safe_file_get_contents')) { function safe_file_get_contents($filename) { $fp = fopen($filename, 'rb'); if ($fp) { flock($fp, LOCK_SH); clearstatcache(); $filesize = filesize($filename); if ($filesize > 0) { $data = fread($fp, $filesize); } flock($fp, LOCK_UN); fclose($fp); return $data; } else { return false; } } } ?>調用樣本: get('yourkey');//yourkey是你為每一個要緩衝的資料定義的緩衝名字 if ($data===false) { $data = '從資料庫取出的資料或很複雜很耗時的弄出來的資料'; $cache->set('yourkey',$data,3600);//緩衝3600秒 } // use your $data ?> |