MVC(Model-View-Controller)是 Web 應用最經典的架構模式。在 PHP 自製框架或理解 Laravel、Symfony 等現代框架核心時,Controller 基礎類別的設計至關重要。本文深度解析路由分發到 Controller 實例化、動作執行、模板渲染、魔術方法應用的完整流程。
<?php
// Route::run() 簡化流程
class Route {
private string $module;
private string $controller;
private string $action;
public function run(): void {
$filePath = APP_PATH . "/controller/{$this->module}/{$this->controller}.php";
if (file_exists($filePath)) {
require_once $filePath;
$controllerClass = "{$this->controller}Controller";
if (class_exists($controllerClass)) {
$controller = new $controllerClass($this); // 注入路由物件
$actionMethod = $this->action . 'Action';
if (method_exists($controller, $actionMethod)) {
$controller->$actionMethod();
return; // 正常執行結束
}
}
}
// 回退預設控制器
$this->fallbackToDefault();
}
}
?>
<?php
abstract class Controller {
// 模板引擎實例(如 Smarty、Twig、Blade、Latte)
protected TemplateEngine $tpl;
// 當前路由資訊
protected Route $route;
// 當前控制器名稱、動作名稱
protected string $controllerName;
protected string $actionName;
// 佈局模板
protected string $layout = 'layout/main';
// 視圖變數容器
protected array $viewVars = [];
public function __construct(Route $route) {
$this->route = $route;
$this->controllerName = $route->getControllerName();
$this->actionName = $route->getActionName();
$this->init();
}
// 初始化鉤子:子類別可覆寫
protected function init(): void {
// 共用初始化:載入設定、檢查權限、設定語系等
}
}
?>
<?php
abstract class Controller {
// ... 前述屬性 ...
// 指派單一變數
public function assign(string $name, mixed $value): void {
$this->viewVars[$name] = $value;
$this->tpl->assign($name, $value);
}
// 批次指派
public function assignMultiple(array $vars): void {
foreach ($vars as $key => $value) {
$this->assign($key, $value);
}
}
// 顯示指定模板(覆寫預設佈局)
protected function display(string $template = null): void {
$template ??= $this->actionName; // 預設對應 action 名稱
$this->tpl->display($template);
}
// 渲染並回傳字串(AJAX、API、PDF 產生用)
protected function fetch(string $template = null): string {
$template ??= $this->actionName;
return $this->tpl->fetch($template);
}
// 渲染部分視圖(局部更新、Widget)
protected function renderPartial(string $partial, array $vars = []): string {
return $this->tpl->fetch("partials/$partial", $vars);
}
}
?>
<?php
abstract class Controller {
// ...
// 允許 $this->title = 'Page Title' 直接指派
public function __set(string $name, mixed $value): void {
$this->assign($name, $value);
}
// 允許 $title = $this->title 讀取
public function __get(string $name): mixed {
return $this->viewVars[$name] ?? null;
}
// isset() 檢查
public function __isset(string $name): bool {
return isset($this->viewVars[$name]);
}
// unset() 清除
public function __unset(string $name): void {
unset($this->viewVars[$name]);
// 模板引擎可能需同步清除
}
}
// 子類別使用
class ArticleController extends Controller {
public function showAction(): void {
$this->title = '文章標題'; // 自動指派
$this->article = $articleData; // 自動指派
$this->display(); // 渲染 article/show.tpl
}
}
?>
<?php
abstract class Controller {
// ...
// 支援動態動作:$this->renderJson($data)、$this->renderXml($data)
public function __call(string $name, array $args): mixed {
if (str_starts_with($name, 'render')) {
$format = strtolower(substr($name, 6)); // json, xml, csv...
return $this->renderFormat($format, $args[0] ?? []);
}
// 動態存取模型關聯:$this->getUserProfile() -> $this->user->profile
if (str_starts_with($name, 'get')) {
$relation = lcfirst(substr($name, 3));
if (property_exists($this, $relation)) {
return $this->$relation;
}
}
throw new BadMethodCallException("Method $name not found");
}
private function renderFormat(string $format, array $data): void {
header("Content-Type: application/$format; charset=utf-8");
match ($format) {
'json' => echo json_encode($data, JSON_UNESCAPED_UNICODE),
'xml' => echo $this->arrayToXml($data),
default => throw new InvalidArgumentException("Unsupported format: $format"),
};
exit;
}
}
?>
利用 __destruct() 在物件銷毀時自動渲染,實現「約定優於配置」:
<?php
abstract class Controller {
// ...
protected bool $rendered = false;
public function __destruct() {
if (!$this->rendered && !$this->isAjaxRequest()) {
$this->renderDefault();
}
}
protected function renderDefault(): void {
$this->rendered = true;
// 自動推斷模板路徑:module/controller/action
$template = "{$this->controllerName}/{$this->actionName}";
$this->display($template);
}
// 手動渲染時標記
protected function display(string $template = null): void {
$this->rendered = true;
parent::display($template);
}
protected function isAjaxRequest(): bool {
return !empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
}
}
?>
<?php
class ProductController extends Controller {
public function __construct(Route $route) {
parent::__construct($route);
// 可在這裡檢查權限、載入服務
}
public function listAction(): void {
$page = (int)($this->route->getParam('page') ?? 1);
$perPage = 20;
$products = ProductService::getPaginated($page, $perPage);
$pagination = Pagination::create($page, $perPage, $products['total']);
$this->assignMultiple([
'products' => $products['data'],
'pagination' => $pagination,
'pageTitle' => '產品列表',
]);
// 自動渲染 product/list.tpl(或由 __destruct 處理)
}
public function detailAction(): void {
$id = (int)$this->route->getParam('id');
$product = ProductService::findById($id);
if (!$product) {
$this->show404();
return;
}
$this->product = $product;
$this->pageTitle = $product->name;
// 自動渲染 product/detail.tpl
}
public function apiListAction(): void {
$products = ProductService::getAll(['status' => 'active']);
$this->renderJson(['data' => $products]); // 動態方法
}
protected function show404(): void {
http_response_code(404);
$this->display('errors/404');
exit;
}
}
?>
| 特性 | 自製基礎 Controller | Laravel Controller | Symfony Controller |
|---|---|---|---|
| 基礎類別 | 自訂 abstract Controller | Illuminate\Routing\Controller | AbstractController |
| 依賴注入 | 手動/建構子注入 | 建構子/方法注入(自動解析) | 建構子/方法注入(自動解析) |
| 回傳值 | void(自動渲染) | Response / View / JsonResponse | Response / View |
| 模板渲染 | $this->display() / 魔術方法 | view() helper / $this->view() | $this->render() |
| 請求存取 | $this->route / $_GET/$_POST | Request $request 參數注入 | Request $request 參數注入 |
| 生命週期鉤子 | __construct, __destruct, init() | Middleware, Policies, FormRequest | Event Listeners, Voters |
indexAction, createAction, storeAction, showAction, editAction, updateAction, destroyAction(RESTful 風格)Controller 基礎類別是 MVC 架構的骨幹,連接路由分發、業務邏輯協調、視圖渲染。從自製框架的魔術方法技巧,到現代框架的依賴注入、中介軟體、表單請求驗證,核心思想始終是關注點分離。理解基礎 Controller 設計原理,能讓你在使用任何框架時都能舉一反三,做出更好的架構決策。