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

Discuz 風格模板引擎封裝類:自動快取與生命週期管理

     編輯:PHP 綜合知識

核心特性

  • 移植 Discuz 模板語法 (循環、條件、變數輸出等)
  • 移除語言包依賴,輕量化
  • 支援模板目錄、快取目錄設定
  • 自動偵測模板檔案修改時間,重新編譯快取
  • 快取生命週期可設定 (分鐘),0 表永久
  • 單例模式存取

使用範例

<?php
require_once 'classes/template.class.php';

$options = [
    'template_dir'   => 'templates/',
    'cache_dir'      => 'templates/cache',
    'auto_update'    => true,   // 模板變更自動更新快取
    'cache_lifetime' => 1,      // 快取壽命 (分鐘),0 = 永久
];
$template = Template::getInstance();
$template->setOptions($options);

// 指派變數
$testArr = ['testa' => 'a', 'testb' => 'b'];

// 載入並輸出模板
include $template->getfile('test.htm');
?>

模板語法速查 (Discuz 風格)

語法說明
{$var}輸出變數
{loop $arr $k $v}...{/loop}陣列迴圈
{if $cond}...{elseif $cond}...{else}...{/if}條件判斷
{eval ...}執行 PHP 代碼
{template header}引入子模板

快取機制說明

  1. 首次載入:解析模板檔 → 產生 PHP 編譯檔存入 cache_dir → include 執行。
  2. 後續請求:比對模板檔 mtime 與快取檔 mtime,若 auto_update=true 且模板較新則重新編譯。
  3. cache_lifetime 控制快取過期;設為 0 則永不重新編譯 (效能最佳,部署時需手動清除快取)。

啟用語言包 (可選)

若需 Discuz 語言包功能,請在 template.class.php 第 172 行取消註解,並在 template.func.php 加入原版 languagevar() 函式。

結語

此封裝類保留 Discuz 模板引擎核心功能,並加入現代化快取策略,適合中小型專案快速導入模板分離架構。

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