PHP 每次請求都需重新編譯腳本、執行邏輯、查詢資料庫。高流量網站若無快取機制,伺服器極易過載。PEAR Cache 提供統一介面,支援多種儲存後端(檔案、共享記憶體、資料庫),並內建函數快取模組,是早期 PHP 專案常用的快取解決方案。(現代專案多改用 Redis、Memcached、APCu、OPcache 組合)。
$ pear install Cache
# 或 composer require pear/cache
核心類別:
Cache:基底抽象類別Cache_Container_*:儲存後端實作(file, shm, db, phplib, dbx)Cache_Function:函數/方法結果快取裝飾器| 容器 | 特點 | 關鍵參數 |
|---|---|---|
file | 檔案系統儲存,最快、最簡單 | cache_dir, filename_prefix |
shm | 共享記憶體,適合單機高併發 | shm_key, shm_size, shm_perm, sem_key |
db | 透過 PEAR DB 抽象層存資料庫 | dsn, cache_table |
phplib | phplib 風格資料庫容器 | db_class, db_file, local_path... |
ext/dbx | PHP dbx 擴充模組資料庫容器 | module, host, db, user, password |
<?php
require_once 'Cache.php';
$options = [
'container' => 'file',
'cache_dir' => '/var/cache/myapp',
'filename_prefix' => 'app_',
];
$cache = new Cache($options);
if (!$cache) die('Cache 初始化失敗');
// 存入(預設壽命 3600 秒)
$cache->save('user_list', $userListData, 'user_cache_group');
// 取得
if ($data = $cache->load('user_list', 'user_cache_group')) {
echo "來自快取";
} else {
$data = fetchUserListFromDB();
$cache->save('user_list', $data, 'user_cache_group');
echo "來自資料庫";
}
// 刪除特定項目
$cache->remove('user_list', 'user_cache_group');
// 清空群組
$cache->flush('user_cache_group');
?>
自動快取任意函數/方法的回傳值,預設使用 file 容器,儲存於 function_cache 目錄。
<?php
require_once 'Cache/Function.php';
$funcCache = new Cache_Function([
'container' => 'file',
'cache_dir' => '/var/cache/myapp/function',
'filename_prefix' => 'func_',
]);
// 快取無參數函數
$result = $funcCache->call('getHeavyConfig');
// 快取有參數函數(參數會序列化為快取鍵一部分)
$result = $funcCache->call('calculateTax', 1000, 'TW');
// 快取物件方法
$result = $funcCache->call([$service, 'fetchReport'], $year, $month);
// 手動清除特定呼叫快取
$funcCache->remove('calculateTax', 1000, 'TW');
?>
將資料庫查詢結果快取到資料庫容器通常無意義(額外查詢開銷)。
檔案容器適合單機、中小流量;共享記憶體適合單機高併發;分散式環境請改用 Redis/Memcached。
| 場景 | 現代替代方案 |
|---|---|
| 頁面/片段快取 | Laravel Cache / Symfony Cache + Redis/Memcached/APCu |
| 資料庫查詢快取 | Eloquent/Doctrine 內建查詢快取 + Redis |
| 函數/方法結果快取 | 自訂裝飾器 + PSR-16 介面(如 symfony/cache) |
| Opcode 快取 | OPcache (PHP 內建,必開) |
| HTTP 快取 | Varnish, Nginx fastcgi_cache, CDN |
PEAR Cache 曾是 PHP 快取標準解法,其「容器抽象 + 函數快取裝飾器」設計思想仍具參考價值。現代專案應優先採用 PSR-6/16 相容的快取庫(symfony/cache, laminas-cache, doctrine/cache)搭配 Redis/APCu,並善用 OPcache 與 HTTP 層快取,構建多層次快取策略。