首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Smarty 快取機制與頁面靜態化原理:多重快取、isCached 與 nocache 標籤

     編輯:PHP 綜合知識

Smarty 快取進階應用

Smarty 提供強大的模板快取功能,可大幅減少資料庫查詢與 PHP 運算。本文說明如何實現「一個模板、多個快取」、快取判斷邏輯,以及局部不快取的處理方式。

一、建立多重快取:使用 request URI 作為快取 ID

<?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} 標籤

模板中需即時顯示的區塊(如使用者登入狀態、評論區),包裹在 {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 端配合:動態資料放在 isCached 判斷外部

<?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 2is_cached()
Smarty 3iscached()

善用快取機制可讓頁面回應速度提升數十倍,但需謹慎設計快取失效策略(如資料更新時清除對應快取檔)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved