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

Smarty 快取技術全解析:全域、區塊、局部三種機制詳解

     編輯:PHP 相關知識

前言

合理運用快取能大幅降低伺服器負載。Smarty 提供靈活的快取機制,本文系統整理啟用方式、清除策略、三種快取模式(全域/區塊/局部)與自訂快取處理器。

一、啟用與基本設定

$smarty->cache_dir = './cache/';      // 快取目錄(需可寫入)
$smarty->caching = 1;                 // 1/true=開啟,0/false=關閉
$smarty->cache_lifetime = 3600;       // 存活秒數,-1=永不過期

二、快取清除方法

$smarty->clear_all_cache();                    // 清除所有
$smarty->clear_cache('index.tpl');             // 清除指定模板
$smarty->clear_cache('index.tpl', $cache_id);  // 清除指定 ID

三、全域快取:全站頁面快取

針對動態參數產生不同快取,使用 cache_id 區分:

$smarty->display('list.html', md5($_SERVER['REQUEST_URI']));
// 將完整 URL(含參數)MD5 作為快取 ID,避免不同參數共用同一快取
關鍵點:若不指定 cache_id,/article.php?id=5 與 /article.php?id=7 會共用同一快取,導致內容錯誤。

四、區塊快取:指定頁面快取、指定頁面不快取

本質是「預設全開,排除不快取頁面」:

// 需要快取的頁面
$smarty->display('index.html', md5($_SERVER['REQUEST_URI']));
$smarty->display('cate.html', md5($_SERVER['REQUEST_URI']));

// 不需要快取的頁面(article.php)
$smarty->clear_cache('article.html');  // 顯式清除、確保不產生快取
$smarty->display('article.html');      // 不帶 cache_id
注意:clear_cache() 與 display() 模板名稱必須一致。

五、局部快取:頁面區塊級快取

本質是「預設全快取,排除動態區塊」。使用 {insert} 標籤實現:

{* PHP 控制器 *}
$time = time();
$smarty->assign('time', $time);
function insert_timeget() { return time(); }
$smarty->display('article.html');

{* 模板 article.html *}
<body>
{$time} <!-- 快取後固定不變 -->
{insert name='timeget'} <!-- 每次請求即時執行,不受快取影響 -->
</body>

原理:定義 insert_名稱() 函數,模板用 {insert name='名稱'} 呼叫,回傳值直接輸出,繞過快取機制。

六、自訂快取處理器

將快取儲存至 Redis、資料庫等自訂儲存體:

$smarty->cache_handler_func = "myCache";
function myCache($action, &$smarty_obj, &$cache_content, $tpl_file=null, $cache_id=null, $compile_id=null) {
    switch($action) {
        case "read":  /* 讀取快取 */ break;
        case "write": /* 寫入快取 */ break;
        case "clear": /* 清除快取 */ break;
    }
}

總結對照表

模式適用場景核心做法
全域快取內容型站點、參數化頁面display(tpl, cache_id),cache_id 含 URL 參數
區塊快取大部分頁面靜態,少數動態動態頁面 clear_cache() + 無 cache_id 的 display()
局部快取頁面大部份可快取,局部即時{insert name='func'} + insert_func() 即時輸出
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved