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

Smarty 3 入門指南:安裝、目錄結構與 MVC 框架整合實戰

     編輯:PHP 綜合知識

一、Smarty 簡明教程

1. 安裝與演示

下載最新版 Smarty(示例為 3.1.12),解壓後將 demo/ 與 libs/ 複製至 Web 根目錄(如 /var/www/yqting/)。重點:必須將 cache/ 和 templates_c/ 設置為可讀寫權限(chmod 777),否則編譯與緩存失效。

啟動 Apache,訪問 https://localhost/yqting/demo/index.php 即可看到演示頁面。

2. 目錄結構解析

yqting/
├── demo/
│   ├── cache/          緩存文件目錄
│   ├── configs/        配置文件目錄
│   ├── index.php       入口文件
│   ├── plugins/        自定義插件
│   ├── templates/      模板文件目錄
│   └── templates_c/    編譯後文件目錄
└── libs/
    ├── debug.tpl       調試模板
    ├── plugins/        核心插件(不可修改)
    │   ├── SmartyBC.class.php  Smarty 2 兼容層
    │   ├── Smarty.class.php    核心類
    │   └── sysplugins/         系統插件(核心功能)

擴展插件:可將自定義插件放入 libs/plugins/,或按 demo/ 結構另建 plugins/、cache/、configs/、templates/、templates_c/ 目錄(後兩者需可寫)。

3. 實現簡單示例

  1. 建立 weibo/ 目錄及子目錄,設置權限。
  2. 模板 index.tpl:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=gb2312">
<title>Smarty</title>
</head>
<body>
username: {$Name}
</body>
</html>
  1. 邏輯 index.php:
<?php
require '../libs/Smarty.class.php';
$smarty = new Smarty();
$username = "Smarty";
$smarty->assign("Name", $username);
$smarty->display('index.tpl');
?>

Smarty 3 構造函數已預設 template_dir、compile_dir、config_dir、cache_dir,無需手動指定。訪問 https://localhost/yqting/weibo/index.php 輸出 username:Smarty。

二、核心程序詳解

代碼片段說明
/**/文件頭註釋,記錄用途、版權、作者、時間,屬良好風格
require_once引入 Smarty 核心類,路徑務必正確
$smarty = new Smarty()實例化 Smarty 對象
$smarty->template_dir指定模板目錄,默認 ./templates/,建議顯式聲明
$smarty->compile_dir指定編譯目錄,默認 ./templates_c/,Linux 下需可寫
$smarty->left_delimiter / right_delimiter定義模板變量分隔符,默認 { },常改為 {# #} 或 <!--{ }--> 避免與 JS 衝突
$smarty->cache_dir緩存目錄,默認 ./cache/,需可寫
$smarty->cache_lifetime緩存有效期(秒),-1 永不過期,0 每次重建,示例設 1 天
$smarty->caching = 1啟用緩存:0 關閉,1 用當前 cache_lifetime,2 用緩存創建時的值
$smarty->assign("name", $val)核心賦值方法,將 PHP 變量映射到模板變量
$smarty->display("index.tpl")解析並輸出模板,文件名相對於 template_dir

執行後 templates_c/ 與 cache/ 會自動生成編譯/緩存文件(以 %% 開頭),切勿手動修改。

三、MVC 框架整合建議

  • 控制器負責業務邏輯、數據獲取,調用 $smarty->assign() 傳遞數據
  • 模型封裝數據庫操作,返回純數據結構
  • 視圖僅包含顯示邏輯,使用 Smarty 標籤、修飾符、區塊函數
  • 統一在基類控制器中初始化 Smarty、設置目錄、分隔符、緩存策略
  • 利用 plugins/ 目錄存放項目專用修飾符、區塊函數,保持模板簡潔

Smarty 作為成熟模板引擎,嚴格分離 PHP 與 HTML,配合 MVC 結構可顯著提升項目可維護性與團隊協作效率。

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