Smarty 等模板引擎核心價值在於分離邏輯與表現:PHP 程式師專注業務邏輯,前端工程師專注頁面設計,雙方互不干擾,團隊協作效率大幅提升。
<?php
class MinSmarty {
var $template_dir = "./templates/"; // 模板目錄
var $compile_dir = "./templates_c/"; // 編譯快取目錄
var $tpl_vars = []; // 變數容器
// 指派變數
function assign($tpl_var, $var = NULL) {
if ($tpl_var !== NULL) $this->tpl_vars[$tpl_var] = $var;
}
// 顯示模板
function display($tpl_file) {
$tpl_path = $this->template_dir . $tpl_file;
$compile_path = $this->compile_dir . "com_" . $tpl_file . ".php";
if (!file_exists($tpl_path)) return false;
// 僅當模板更新或快取不存在時重新編譯
if (!file_exists($compile_path) || filemtime($tpl_path) > filemtime($compile_path)) {
$content = file_get_contents($tpl_path);
// 將 {$var} 替換為 tpl_vars['var']; ?>
$pattern = '/\{\s*\$([a-zA-Z_][a-zA-Z0-9_]*)\s*\}/i';
$replace = '<?php echo $this->tpl_vars["${1}"];?>';
$new_content = preg_replace($pattern, $replace, $content);
file_put_contents($compile_path, $new_content);
}
include_once($compile_path);
}
}
?>
intro.php(控制器)
<?php
include_once("MinSmarty.class.php");
$title = "這裡是標題";
$content = "這裡是內容 111111";
$tpl = new MinSmarty();
$tpl->assign("title", $title);
$tpl->assign("content", $content);
$tpl->display("intro.tpl");
?>
intro.tpl(模板)
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>{$title}</title>
</head>
<body>
{$content}
</body>
</html>
assign() 將變數存入 $tpl_vars 陣列。display() 讀取 .tpl,用正則將 {$var} 編譯為 PHP 輸出語句,產生 com_intro.tpl.php 快取檔。include_once 快取檔,跳過正則解析,效能極佳。<title><?php echo $this->tpl_vars["title"];?></title>延伸閱讀:Smarty 入門教程、PHP 模板技術總結、PDO 資料庫技巧、PHP 運算符、網絡編程、基礎語法、OOP 入門、字串用法、MySQL 入門、常見資料庫操作匯總。