Smarty 模板引擎內建強大的快取機制,能大幅降低伺服器負載。本文詳細說明三種快取層級的設定與實作:全域快取、區塊快取(部分快取)、局部快取(動態區塊)。
$smarty->cache_dir = './cache/'; // 快取目錄(需可寫入)
$smarty->caching = true; // 1/true 開啟,0/false 關閉
$smarty->cache_lifetime = 3600; // 快取存活秒數,-1 永不過期
最簡單,整個模板輸出快取。關鍵在於快取 ID必須包含動態參數(如查詢字串),否則不同參數會共用同一快取。
$cacheId = md5($_SERVER['REQUEST_URI']); // 含查詢字串的完整 URL 雜湊
$smarty->display('list.html', $cacheId);
陷阱: list.php?cat=1 和 list.php?cat=2 若用同一快取 ID,會導致內容錯誤。務必用包含參數的 URL 產生快取 ID。
本質是「預設全域快取,特定頁面排除」。
// 1.php、2.php 正常快取
$smarty->display('1.html', $cacheId);
$smarty->display('2.html', $cacheId);
// 3.php 不快取:在 display 前清除該模板快取
$smarty->clear_cache('3.html'); // 模板名需與 display 一致
$smarty->display('3.html'); // 不傳快取 ID 或傳同樣 ID 皆可
注意: clear_cache() 必須在 display() 前或後呼叫皆可,參數必須一致。
本質是「預設快取,特定區塊排除」。使用 {insert} 標籤配合 insert_ 前綴函數。
function insert_currentTime() {
return date('Y-m-d H:i:s'); // 每次呼叫返回當前時間
}
$smarty->assign('staticTime', time()); // 這個會被快取
$smarty->display('index.html');
<!-- 這行會被快取,重新整理不變 -->
靜態時間:{$staticTime}
<!-- 這行不會被快取,每次重新整理都更新 -->
動態時間:{insert name='currentTime'}
insert_函數名() 函數,回傳動態內容。{insert name='函數名'} 呼叫。$smarty->clear_all_cache():清除所有快取$smarty->clear_cache('tpl.html', $cacheId):清除特定模板+ID$smarty->clear_cache('tpl.html'):清除該模板所有 ID/tmp 或記憶體檔案系統(tmpfs)提升 I/O。