2009-11-04 15:54

[PHP] 利用檔案作資料快取

當沒辦法架設好用的快取機制時
又想利用快取的方式降低 DB 負荷時
不妨使用檔案的方式處理

這裡使用 serialize() 這個函數將變數轉成字串
然後存到文件裡做快取存放
這個函數跟 $_SEEION 用的是一樣的函數

<?php
class Cache {
private static $_savePath = '.';
private static $_cached = true;

/**初始化
* @param string $savePath 暫存檔的存放路徑
* @param bool $cached 是否啟用暫存,這個設定可以快速關閉所有暫存的使用
*/
public static function start($savePath='.', $cached=true ) {
self::$_savePath = $savePath.'/';
self::$_cached = (bool)$cached;
}


/**取得暫存資料
* @param string $index 暫存檔的名稱
* @return var 所暫存的資料,當暫存不存在時回傳 null
*/
public static function load($index) {
if(!self::$_cached){ return null; }

$filePath = self::$_savePath.$index.'.cache';
if(file_exists($filePath)){
$value = file_get_contents($filePath);
return unserialize($value);

}else{
return null;
}
}


/**儲存暫存資料
* @param string $index 暫存檔的名稱
* @param var $value 需要暫存的資料
*/
public static function save($index, $value) {
$filePath = self::$_savePath.$index.'.cache';
$value = serialize($value);

try {
file_put_contents($filePath ,$value);
} catch (Exception $e) {
/*檔案讀取失敗*/
throw $e;
}
}

/**清除暫存資料
* @param string $index 暫存檔的名稱,當設定為 null 時清除所有 Cache
*/
public static function remove($index=null) {
/*清除所有 Cache*/
if($index===null){
$dir = opendir(self::$_savePath);
while (false !== ($fileName = readdir($dir))) {
if(strpos($fileName,'.cache')===false) {
continue;
}elseif(file_exists($filePath = self::$_savePath.$fileName)){
unlink($filePath);
}
}
closedir($dir);


/*清除指定 Cache*/
}elseif(file_exists($filePath = self::$_savePath.$index.'.cache')){
unlink($filePath);
}
}
}


使用範例:

<?php
/**(初始化)變數快取類別,設定存放的目錄*/
Cache::start('/www/cache');


if(!$sysSetting = Cache::load('sysSetting')){
/*取得資料*/
$sysSetting = $dbAdapter->query("
SELECT `Group`, `Name`, `Value`
FROM `system_setting`
")->fetchAll();


/*快取資料*/
Cache::save('sysSetting', $sysSetting);
}

0 回應: