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

PHP 檔案快取 Smarty 模板應用實例詳解

     編輯:PHP 相關知識

PHP 檔案快取 Smarty 模板應用實例詳解

一、啟用快取

將 caching 設為 true,指定 cache_dir。使用 cache_lifetime 設定快取存活秒數。若同一頁面需多組快取,於 display 或 fetch 傳入第二參數 cache_id:

$smarty->display('index.tpl', $my_cache_id);

可針對不同 $_GET 產生不同快取。

二、清除快取

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

三、自訂快取處理器

設定 cache_handler_func 使用自訂函式處理快取:

$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":  // 讀取快取內容
        case "write": // 寫入快取
        case "clear": // 清空快取
    }
}

建議以 md5($tpl_file.$cache_id.$compile_id) 作為唯一快取 ID,可搭配 gzcompress/gzuncompress 壓縮。

四、區域關閉快取

使用 {insert} 或 register_block 讓特定區塊不被快取。

// 區塊外掛範例:block.cacheless.php
function smarty_block_cacheless($param, $content, &$smarty) { return $content; }

模板中使用:{cacheless} 未快取內容 {/cacheless}。

完整範例

<?php
include('Smarty.class.php');
$smarty = new Smarty;
$smarty->caching = true;
$smarty->cache_lifetime = 6;
$smarty->display('cache.tpl');
?>
// cache.tpl
已經快取的: {$smarty.now}<br>
{cacheless}
沒有快取的: {$smarty.now}
{/cacheless}

透過區塊外掛靈活控制快取範圍,提升效能同時保持動態內容即時性。

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