| 類 | 用途 |
| Cache_Lite | 核心:`get`/`save`/`remove`/`clean`,資料快取 |
| Cache_Lite_Output | 輸出緩衝快取:`start`/`end` 自動捕獲 `ob_get_contents` |
| Cache_Lite_Function | 函數結果快取:`call('func', $args)` |
| Cache_Lite_File | 檔案依賴快取:來源檔變更自動失效 |
通用選項
$options = [
'cacheDir' => '/var/www/cache/', // 絕對路徑,需可寫
'lifeTime' => 3600, // 秒,0=永久
'fileLocking' => true, // 檔案鎖防並發損壞
'writeControl' => true, // 寫入後驗證讀取
'readControl' => true, // 讀取時驗證校驗和
'readControlType' => 'crc32', // 'md5'|'crc32'|'strlen'
'hashedDirectoryLevel' => 2, // 子目錄層級分散檔案 (inode 優化)
'automaticCleaningFactor' => 100, // 1% 機率觸發自動清理過期
'pearErrorMode' => CACHE_LITE_ERROR_DIE, // 錯誤模式
];
範例 1:資料快取 (Cache_Lite)
require_once 'Cache/Lite.php';
$cache = new Cache_Lite($options);
$id = 'homepage_articles';
if ($data = $cache->get($id)) {
echo "From cache\n";
} else {
echo "Rebuilding...\n";
$data = fetchArticlesFromDB(); // 你的查詢邏輯
$cache->save($data, $id);
}
renderTemplate($data);
範例 2:輸出快取 (Cache_Lite_Output) — 含模板渲染
require_once 'Cache/Lite/Output.php';
$cache = new Cache_Lite_Output($options);
$id = 'homepage_html';
if (!$cache->start($id)) {
// 快取未命中,執行業務邏輯 + 模板
$articles = fetchArticlesFromDB();
include 'templates/homepage.php'; // 直接 echo 輸出
$cache->end(); // 自動捕獲輸出並存檔
}
// 命中時 start() 直接輸出快取內容並返回 true,跳過 if 區塊
進階:標籤群組失效 (Cache_Lite::clean)
// 存入時指定群組
$cache->save($data, 'article_123', ['articles', 'user_456']);
// 更新文章 123 後,只清除相關群組
$cache->clean('articles'); // 清除所有文章快取
$cache->clean('user_456'); // 清除用戶 456 相關快取
$cache->clean(); // 清除所有 (慎用)
效能與避坑指南
- 快取目錄放 tmpfs (記憶體盤):`mount -t tmpfs -o size=512m tmpfs /var/www/cache` → 近乎記憶體速度,重啟自動清理。
- 避免 `lifeTime=0` 永久快取:配合標籤失效或 `Cache_Lite_File` 監控來源檔變更。
- 高併發熱點鍵:單飛重建 (Single Flight) — 用 `fileLocking` + 額外 `lock` 檔或 Redis `SETNX` 只讓一個進程重建,其他進程等待或返回舊資料。
- 大對象 (>1MB):改用 Redis/Memcached,檔案 I/O 成瓶頸。
- 序列化改用 igbinary:`$cache->setOption('serializer', 'igbinary')` (需編譯支援),體積減 30%、速度提升。
適用場景對比
| 場景 | 推薦方案 |
| 單機/少量伺服器、資料較小、部署簡單 | Cache_Lite (檔案) |
| 叢集、高併發、大對象、需原子操作 | Redis / Memcached |
| 靜態頁面片段、模板渲染結果 | Cache_Lite_Output |
| 昂貴函數計算結果 (如報表聚合) | Cache_Lite_Function |
- 上一篇文章: PEAR 核心概念速覽:套件庫、編碼標準、基類框架 (與 151434 互補)
- 下一篇文章: PEAR 安裝與環境配置全攻略:include_path 設定、go-pear、Composer 共存
Copyright ©
程式碼之家 All Rights Reserved