phpFastCache 是一個輕量級、開源的 PHP 快取庫,單一檔案即可整合至現有專案。它支援多種快取驅動:APC、Memcache、Memcached、WinCache、Files、PDO、MPDO、SQLite、XCache 等,並提供統一 API,切換快取後端無需修改業務邏輯。
<?php
// 設定檔中引入
include("phpfastcache/phpfastcache.php");
// 設定預設快取驅動,"auto" 會自動偵測最佳可用驅動
phpFastCache::setup("storage", "auto");
// 取得快取實例
$cache = phpFastCache();
最常見的使用模式是「先查快取,無資料再查資料庫/ API,再寫入快取」:
<?php
// 嘗試從快取取得商品頁面資料
$products = $cache->get("product_page");
if ($products === null) {
// 快取未命中,執行資料庫查詢或業務邏輯
$products = getProductsFromDB(); // YOUR DB QUERIES
// 寫入快取,有效期 600 秒(10 分鐘)
$cache->set("product_page", $products, 600);
}
// 輸出內容
echo $products;
<?php
include("phpfastcache/phpfastcache.php");
$cache = phpFastCache("memcached"); // 指定使用 Memcached
$results = $cache->get("youtube_api_keyword");
if ($results === null) {
$results = curl_get("https://www.youtube.com/api/json/url/keyword/page");
// 快取 24 小時,減少 API 呼叫次數
$cache->set("youtube_api_keyword", $results, 3600 * 24);
}
foreach ($results as $video) {
// 處理輸出
}
<?php
// 使用 Files 驅動進行全頁快取
$keyword = md5($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING']);
$html = __c("files")->get($keyword);
if ($html === null) {
ob_start();
// 這裡放置所有頁面邏輯:資料庫查詢、模板渲染等
// ...
$html = ob_get_contents();
// 快取 30 分鐘
__c("files")->set($keyword, $html, 1800);
}
echo $html;
<?php
$cache = phpFastCache("files");
$html = $cache->widget_1; // 魔術屬性存取
if ($html === null) {
$html = renderWidget(); // 渲染元件
// 魔術屬性寫入:array(內容, 過期秒數)
$cache->widget_1 = array($html, 1800);
}
echo $html;
<?php
// 設定檔
include("phpfastcache/phpfastcache.php");
phpFastCache::$storage = "auto";
$cache1 = phpFastCache(); // 預設驅動
$cache2 = __c("memcache"); // 指定 Memcache
$cache3 = new phpFastCache("apc"); // 指定 APC
// 設定 Memcache 伺服器叢集
$servers = array(
array("127.0.0.1", 11211, 100),
array("128.5.1.3", 11215, 80)
);
$cache2->option("server", $servers);
// 多種寫入方式
$cache1->set("key1", "value", 300);
$cache2->key2 = array("value", 600);
__c()->key3 = array("data", 3600*24);
// 多種讀取方式
$data = $cache1->get("key1");
$data = $cache2->key2;
$data = __c()->key3;
$data = __c()->get("key4");
// 跨驅動操作
$cache1 = phpFastCache("files");
$cache1->set("key1", $value, $time);
$cache1->memcache->set("key1", $value, $time);
$cache1->apc->set("whatever", $value, 300);
// 批次操作
$list = $cache1->getMulti(array("key1","key2","key3"));
$cache2->setMulti(
array("key1","value1", 300),
array("key2","value2", 600),
array("key3","value3", 1800)
);
| 驅動名稱 | 適用場景 | 備註 |
|---|---|---|
| apc | 單機高效能 | 需安裝 APCu 擴展 |
| memcache / memcached | 分散式、多伺服器 | 生產環境首選 |
| files | 簡單部署、無額外依賴 | 效能受限於磁碟 I/O |
| pdo / mpdo | 資料庫為基礎快取 | 適合無法安裝擴展的環境 |
| sqlite | 輕量級本地快取 | 檔案基礎,無需獨立服務 |
| wincache | Windows IIS 環境 | Windows 平台優化 |
| xcache | 舊版 PHP 環境 | 已較少使用 |
product:list:page_1、user:profile:123phpFastCache 以其簡潔的 API 和豐富的驅動支援,成為 PHP 專案快速導入快取機制的優選方案。無論是小型專案的檔案快取,還是大型分散式系統的 Memcached 叢集,都能透過統一介面無縫切換。