Smarty 提供多層次快取策略,透過 caching、cache_lifetime、cache_id、{insert} 等機制,可靈活控制頁面哪些部分需快取、哪些需即時更新。
<?php
$smarty->cache_dir = './cache/';
$smarty->caching = true; // 或 1/2 (Smarty 3/4)
$smarty->cache_lifetime = 3600; // 秒,-1 永不過期
// 顯示時帶入唯一 cache_id(如 URL 參數 MD5)
$smarty->display('list.html', md5($_SERVER['REQUEST_URI']));
?>
不同 cache_id 產生獨立快取檔,解決同模板不同參數(如 ?id=5 vs ?id=7) 共用快取問題。
<?php
$smarty->clear_all_cache(); // 全部
$smarty->clear_cache('index.tpl'); // 指定模板
$smarty->clear_cache('index.tpl', $cache_id); // 指定模板+ID
?>
需快取的頁面正常 display();不需快取的頁面在 display() 前呼叫 clear_cache() 強制不使用快取。
<?php
// article.php 不快取
$smarty->clear_cache('article.html');
$smarty->display('article.html');
?>
頁面整體快取,但特定區塊(如即時時間、購物車數量)需動態。定義 insert_名稱() 函數,模板用 {insert name='名稱'} 調用,該區塊不受快取影響。
<?php
function insert_timeget() { return date('H:i:s'); }
$smarty->assign('time', '靜態時間');
$smarty->display('article.html');
?>
{$time}
{insert name='timeget'}
將快取存儲導向 Redis、Memcached、資料庫等。
<?php
$smarty->cache_handler_func = 'myCache';
function myCache($action, &$smarty, &$content, $tpl_file, $cache_id, $compile_id) {
$key = md5($tpl_file . $cache_id . $compile_id);
switch ($action) {
case 'read': $content = Redis::get($key); return !!$content; break;
case 'write': return Redis::setex($key, $smarty->cache_lifetime, $content); break;
case 'clear': return Redis::del($key); break;
}
}
?>