Smarty 提供強大的模板快取功能,可大幅減少資料庫查詢與 PHP 運算。本文說明如何實現「一個模板、多個快取」、快取判斷邏輯,以及局部不快取的處理方式。
<?php
// 顯示模板時傳入第二個參數作為快取 ID
$smarty->display('demo.tpl', $_SERVER['REQUEST_URI']);
不同 URL 參數會產生獨立的快取檔案,實現同一模板服務多種內容。
<?php
// Smarty 2.x
if (!$smarty->is_cached('demo.tpl', $_SERVER['REQUEST_URI'])) {
// 只有快取不存在時才執行資料庫查詢
$data = $db->query('SELECT * FROM articles');
$smarty->assign('articles', $data);
}
$smarty->display('demo.tpl', $_SERVER['REQUEST_URI']);
// Smarty 3.x 方法名稱不同
if (!$smarty->iscached('demo.tpl', $_SERVER['REQUEST_URI'])) {
// ...
}
模板中需即時顯示的區塊(如使用者登入狀態、評論區),包裹在 {nocache} 區塊中:
{* 模板 demo.tpl *}
<div class="header">
歡迎,{nocache}{$user.name}{/nocache} <!-- 每次重新渲染 -->
</div>
<div class="content">
{$article.body} <!-- 走快取 -->
</div>
<div class="comments">
{nocache}
{foreach $comments as $c}
<p>{$c.text}</p>
{/foreach}
{/nocache}
</div>
<?php
// 這些動態資料無論快取是否存在都要重新取得
$sessionUser = getCurrentUser();
$latestComments = getLatestComments();
if (!$smarty->iscached('demo.tpl', $cacheId)) {
$smarty->assign('article', getArticle($id));
}
$smarty->assign('user', $sessionUser);
$smarty->assign('comments', $latestComments);
$smarty->display('demo.tpl', $cacheId);
| 版本 | 快取判斷方法 |
|---|---|
| Smarty 2 | is_cached() |
| Smarty 3 | iscached() |
善用快取機制可讓頁面回應速度提升數十倍,但需謹慎設計快取失效策略(如資料更新時清除對應快取檔)。