首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 手把手實作最簡單 MVC 框架:從零理解核心架構

     編輯:PHP 相關知識

MVC 核心流程

  1. 瀏覽器 發起請求 → 控制器
  2. 控制器 選擇 模型 處理資料
  3. 模型 回傳資料 → 控制器
  4. 控制器 選擇 視圖 渲染
  5. 視圖 顯示資料 → 瀏覽器

目錄結構


mvc-demo/
├─ index.php          # 入口
├─ Controller/
│  └─ TestController.php
├─ Model/
│  └─ TestModel.php
├─ View/
│  └─ TestView.php

核心類別實作

1. 模型 - 負責資料邏輯

<?php
// Model/TestModel.php
class TestModel {
    public function getMessage(): string {
        // 實際專案這裡會查資料庫
        return "Hello from Model at " . date('Y-m-d H:i:s');
    }
}

2. 視圖 - 負責呈現

<?php
// View/TestView.php
class TestView {
    public function render(string $data): void {
        // 簡單輸出,實際會 include 模板檔
        echo "

View Output

"; echo "

{$data}

"; } }

3. 控制器 - 協調者

<?php
// Controller/TestController.php
require_once __DIR__ . '/../Model/TestModel.php';
require_once __DIR__ . '/../View/TestView.php';

class TestController {
    public function show(): void {
        // 1. 選擇模型
        $model = new TestModel();
        // 2. 取得資料
        $data = $model->getMessage();
        // 3. 選擇視圖
        $view = new TestView();
        // 4. 渲染輸出
        $view->render($data);
    }
}

4. 入口檔 - 路由分發

<?php
// index.php
require_once __DIR__ . '/Controller/TestController.php';

$controller = new TestController();
$controller->show();

執行結果

瀏覽 https://localhost/mvc-demo/ 顯示:


View Output
Hello from Model at 2024-01-15 14:30:00

進階:加入簡易路由與自動載入

<?php
// index.php 升級版
spl_autoload_register(function ($class) {
    $file = __DIR__ . '/' . str_replace('\\', '/', $class) . '.php';
    if (file_exists($file)) require_once $file;
});

// 簡單路由:?c=Test&a=show
$controllerName = ($_GET['c'] ?? 'Test') . 'Controller';
$action         = $_GET['a'] ?? 'show';

$class = "Controller\\{$controllerName}";
if (class_exists($class)) {
    $controller = new $class();
    if (method_exists($controller, $action)) {
        $controller->$action();
    } else {
        http_response_code(404);
        echo "Action {$action} not found";
    }
} else {
    http_response_code(404);
    echo "Controller {$controllerName} not found";
}

現代框架的關鍵差異

特性本教學極簡版現代框架
依賴管理require_onceComposer + PSR-4 自動載入
路由手動 $_GET路由集合、中介軟體、屬性路由
模型純類別ORM、Repository、Entity、遷移
視圖echo 字串模板引擎、佈局、元件、資料綁定
請求/回應超全域變數PSR-7 Request/Response 物件
依賴注入new 硬編碼容器、自動配線、介面綁定

學習建議

  1. 先跑通這個極簡版,理解「職責分離」核心。
  2. 嘗試加入:資料庫連線 (PDO)、輸入驗證、錯誤處理、Session。
  3. 閱讀 Laravel 或 Symfony 原始碼,觀察如何擴充上述概念。
  4. 實務專案直接使用成熟框架,不要重複造輪子。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved