很多開發者混淆「編譯」與「緩存」:
<?php $smarty->cache_dir = "/caches/"; // 緩存目錄(需可寫) $smarty->caching = true; // 開啟緩存 $smarty->cache_lifetime = 3600; // 緩存壽命(秒) ?>
如文章詳情頁,同一模板對應不同文章 ID:
$smarty->display('article.tpl', $_GET['article_id']);
// 第二參數為 cache_id,自動生成獨立緩存文件
if (!$smarty->is_cached('article.tpl', $article_id)) {
// 僅在緩存未命中時查詢數據庫
$article = $db->getArticle($article_id);
$smarty->assign('article', $article);
}
$smarty->display('article.tpl', $article_id);
$smarty->clear_all_cache(); // 清除所有
$smarty->clear_cache('article.tpl'); // 清除模板所有緩存
$smarty->clear_cache('article.tpl', $cache_id); // 清除指定 cache_id
定義處理函數:function insert_xxx($params, &$smarty),模板中 {insert name=xxx}。
特點:每次請求都執行,不受緩存影響。
// 定義 block 處理函數
function smarty_block_dynamic($params, $content, &$smarty) {
return $content; // 直接返回內容,不緩存
}
// 註冊:第三參數 false 表示不緩存
$smarty->register_block('dynamic', 'smarty_block_dynamic', false);
模板使用:
{dynamic}這裡的內容每次都會重新執行{/dynamic}
<?php
function smarty_block_dynamic($params, $content, &$smarty) {
return $content;
}
?>
需修改 Smarty_Compiler.class.php 將該 block 預設緩存關閉:
// 找到此行並修改
if ($tag_command == 'dynamic')
$this->_plugins['block'][$tag_command] = array($plugin_func, null, null, null, false);
else
$this->_plugins['block'][$tag_command] = array($plugin_func, null, null, null, true);
function smarty_function_current_time($params, &$smarty) {
return date("Y-m-d H:i:s");
}
$smarty->register_function('current_time', 'smarty_function_current_time', false);
模板:{current_time} 每次請求輸出當前時間。
/caches/
└── article.tpl/
├── 123.php // cache_id = 123
├── 456.php
└── .htaccess // 防止直接訪問
$smarty->caching = false;clear_cache()Smarty 緩存機制靈活強大,關鍵在於「識別什麼可以緩存、什麼必須動態」,配合 is_cached() 與局部不緩存技術,能將頁面響應從百毫秒級壓縮到毫秒級。