傳統 PHP 頁面佈局:
<?php require 'header.php'; ?>
<main>頁面內容</main>
<?php require 'footer.php'; ?>
缺點:變量作用域汙染、難以傳參、邏輯與視圖混雜、無法單元測試。
<?php
// layout.php
function renderHeader(string $title, array $meta = []): void {
// 可在此處理 CSRF Token、SEO 標簽、資源版本號等
<?php ob_start(); ?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= htmlspecialchars($title) ?></title>
<?php foreach ($meta as $name => $content): ?>
<meta name="<?= $name ?>" content="<?= htmlspecialchars($content) ?>">
<?php endforeach; ?>
<link rel="stylesheet" href="/assets/app.css?v=<?= APP_VERSION ?>">
</head>
<body>
<header><h1><?= htmlspecialchars($title) ?></h1></header>
<?php echo ob_get_clean(); ?>
'...']);
?>
<article>...</article>
<?php
/**
* 簡易模板渲染器:提取變量到局部作用域,捕獲輸出
*/
function view(string $template, array $data = []): string {
extract($data, EXTR_SKIP); // 將 $data['title'] 變為 $title
$file = __DIR__ . "/templates/$template.php";
if (!is_file($file)) {
throw new RuntimeException("Template not found: $file");
}
ob_start();
try {
include $file;
} catch (Throwable $e) {
ob_end_clean();
throw $e;
}
return ob_get_clean();
}
// templates/article.php
// 可直接使用 $title, $content, $tags
// <h1><?= htmlspecialchars($title) ?></h1>
// <div><?= $content ?></div>
// 控制器
echo view('layout', [
'title' => '文章標題',
'content' => view('article', ['title' => '...', 'content' => '...']),
'user' => $currentUser,
]);
| 維度 | require/include | 函數封裝 | 模板渲染函數 |
|---|---|---|---|
| 變量傳遞 | 全局作用域隱式共享 | 顯式參數 | extract() 顯式注入 |
| 作用域隔離 | 無 | 函數作用域 | 函數作用域 + extract |
| 可測試性 | 難 | 易 (Mock 參數) | 易 (返回字符串斷言) |
| 佈局嵌套 | 手動 include 順序 | 函數調用順序 | 組合調用 view('layout', ['body' => view('child')]) |
| 輸出控制 | 直接輸出 | ob_start 捕獲 | ob_start 捕獲返回 |
| 適用場景 | 極簡頁面、歷史遷移 | 中小項目、無框架 | 中型項目、API 響應、郵件模板 |
@extends('layout')、@section('content')、{{ $var }} 自動轉義、@component、@include。{% extends 'base.html.twig' %}、{{ var|escape }}、沙箱模式、繼承塊。{extend name="layout"}、{block name="content"}、{$var}。readonly class DTO + __invoke 渲染器,結合屬性掛載元數據。?v=hash 或 ?v=版本號,解決緩存。#[Attribute] 元數據。