標籤:徹底刪除 md5 完成 緩衝 array key host cal 反序
// 自訂緩衝類class Cache_Filesystem { // 緩衝寫儲存 function set ($key, $data, $ttl) { //開啟檔案為讀/寫入模式 $h = fopen($this->get_filename($key), ‘a+‘); if (!$h) throw new Exception("Could not write to cache"); flock($h, LOCK_EX); //寫鎖定,在完成之前檔案關閉不可再寫入 fseek($h, 0); // 讀到檔案頭 ftruncate($h, 0); //清空檔案內容 // 根據生存周期$ttl寫入到期時間 $data = serialize(array(time()+$ttl, $data)); if (fwrite($h, $data) === false) { throw new Exception(‘Could not write to cache‘); } fclose($h); } // 讀取快取資料,如果未取出返回失敗資訊 function get ($key) { $filename = $this->get_filename($key); if ( !file_exists( $filename ) ) { return false; } $h = fopen($filename, ‘r‘); if (!$h) return false; // 檔案讀取鎖定 flock($h, LOCK_SH); $data = file_get_contents($filename); fclose($h); $data = @unserialize($data); if ( !$data ) { // 如果還原序列化失敗,則徹底刪除該檔案 unlink($filename); return false; } if (time() > $data[0]) { // 如果緩衝已經到期,則刪除檔案 unlink($filename); return false; } } // 清除緩衝 function clear ( $key ) { $filename = $this->get_filename($key); if (file_exists($filename)) { return unlink($filename); } else { return false; } } // 擷取快取檔案 private function get_filename ($key) { return ‘./cache/‘ . md5($key); }}
調用
require ‘./4.3-cache_class.php‘;// 建立新對象$cache = new Cache_Filesystem();function getUsers () { global $cache; // 自訂一個緩衝key唯一標識 $key = ‘getUsers:selectAll‘; // 檢測資料是否緩衝 if ( !$data = $cache->get( $key ) ) { // 如果沒有緩衝,則擷取新資料 $db_host = ‘localhost‘; $db_user = ‘root‘; $db_password = ‘root‘; $database = ‘ecshop_test‘; $conn = mysql_connect( $db_host, $db_user, $db_password); mysql_select_db($database); //執行sql查詢 $result = mysql_query("select * from ecs_users"); $data = array(); // 將擷取到的資料放入數組$data中 while ( $row = mysql_fetch_assoc($result)) { $data[] = $row; } // 儲存該資料到緩衝中,生存周期為10分鐘 $cache->set($key, $data, 10); } return $data;}try { $users = getUsers(); print_r($users); $key = ‘getUsers:selectAll‘; //$cache->clear($key);} catch (Exception $e) { print $e->getMessage();}
php資料緩衝到檔案類設計