... 交織 HTML,邏輯與呈現難以分辨。| 任務 | 描述 | 關鍵指標 |
|---|---|---|
| 資料與顯示分離 | PHP 僅負責取得/處理資料(Model),模板僅負責呈現(View) | 模板檔零 PHP 邏輯(僅含輸出標籤、迴圈、條件) |
| 團隊分工協作 | 美工維護模板、程式師維護控制器、架構師維護核心庫 | 介面契約文件化(變數名、區塊名、資料結構) |
Model - getnews.php:
<?php
// 僅負責資料存取,回傳陣列
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$stmt = $pdo->query('SELECT id, title, created_at FROM news ORDER BY id DESC LIMIT 10');
$news = $stmt->fetchAll(PDO::FETCH_ASSOC);
View - shownesw.php:
<html><head><title>新聞列表</title></head><body>
<ul>
<?php foreach ($news as $n): ?>
<li><a href="view.php?id=<?=$n['id']?>"><?=$n['title']?></a> <small><?=$n['created_at']?></small></li>
<?php endforeach; ?>
</ul>
</body></html>
Controller - listnews.php:
<?php
include 'getnews.php'; // Model
include 'shownesw.php'; // View(直接輸出)
此即最純粹的「PHP 標籤模板」,雖無編譯快取,但已完成 M/V/C 分離,適合微型專案。
模板 shownews.tpl:
<html><body>
<ul>
{news_rows}
</ul>
</body></html>
控制器:
<?php
include 'getnews.php';
$rows = '';
foreach ($news as $n) {
$rows .= "<li><a href='view.php?id={$n['id']}'>{$n['title']}</a> <small>{$n['created_at']}</small></li>";
}
$tpl = file_get_contents('shownews.tpl');
echo str_replace('{news_rows}', $rows, $tpl);
美工完全不見 PHP 程式碼,但控制器需手工拼接 HTML 字串,彈性受限。
base.tpl 佈局,子模板 {extends 'base.tpl'} 僅覆寫區塊,消除重複 HTML。{_('Hello')} 翻譯函式整合。模板技術核心價值在於「契約化介面」與「關注點分離」。從原生標籤到現代引擎,形式雖變,但「Model 只管資料、View 只管呈現、Controller 只管串接」的 MVC 三角關係始終不變。團隊若能建立「變數契約文件」並貫徹平行開發流程,即能發揮模板引擎最大效益。