萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP MVC 架構核心:Controller 基礎類別設計、路由分發與模板渲染機制深度解析

前言

MVC(Model-View-Controller)是 Web 應用最經典的架構模式。在 PHP 自製框架或理解 Laravel、Symfony 等現代框架核心時,Controller 基礎類別的設計至關重要。本文深度解析路由分發到 Controller 實例化、動作執行、模板渲染、魔術方法應用的完整流程。

路由分發到 Controller 的完整流程

1. 路由解析確定 MCA(Module/Controller/Action)

<?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();
    }
}
?>

基礎 Controller 類別設計

核心屬性與建構子

<?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);
    }
}
?>

魔術方法在 Controller 中的妙用

__set() / __get():簡化模板變數指派

<?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
    }
}
?>

__call():動態動作方法、欄位存取器

<?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';
    }
}
?>

實際 Controller 實作範例

<?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;
    }
}
?>

現代框架對比:Laravel / Symfony Controller 設計

特性自製基礎 ControllerLaravel ControllerSymfony Controller
基礎類別自訂 abstract ControllerIlluminate\Routing\ControllerAbstractController
依賴注入手動/建構子注入建構子/方法注入(自動解析)建構子/方法注入(自動解析)
回傳值void(自動渲染)Response / View / JsonResponseResponse / View
模板渲染$this->display() / 魔術方法view() helper / $this->view()$this->render()
請求存取$this->route / $_GET/$_POSTRequest $request 參數注入Request $request 參數注入
生命週期鉤子__construct, __destruct, init()Middleware, Policies, FormRequestEvent Listeners, Voters

最佳實踐原則

  1. Controller 薄化:業務邏輯移至 Service/Action 類別,Controller 僅處理 HTTP 層面(請求解析、回應組裝)
  2. 單一職責:一個 Controller 對應一個資源/聚合根
  3. 動作方法命名:indexAction, createAction, storeAction, showAction, editAction, updateAction, destroyAction(RESTful 風格)
  4. 輸入驗證前置:使用 FormRequest、DTO、Validator 而非在 Controller 寫驗證邏輯
  5. 錯誤處理統一:拋出例外交由全域異常處理器,Controller 不捕獲業務異常
  6. 避免在 __destruct 進行複雜邏輯:除錯困難、例外處理棘手,現代框架改用 Middleware/Event

結語

Controller 基礎類別是 MVC 架構的骨幹,連接路由分發、業務邏輯協調、視圖渲染。從自製框架的魔術方法技巧,到現代框架的依賴注入、中介軟體、表單請求驗證,核心思想始終是關注點分離。理解基礎 Controller 設計原理,能讓你在使用任何框架時都能舉一反三,做出更好的架構決策。

copyright © 萬盛學電腦網 all rights reserved