萬盛學電腦網

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

PHP MVC 框架核心原理:從零手寫一個微型框架

MVC (Model-View-Controller) 是 Web 應用最經典的架構模式。理解其核心原理——**單一入口、路由分發、控制器調度、視圖渲染、模型數據**——能幫助你深度掌握 Laravel、ThinkPHP、Symfony 等主流框架的運行機制。本文從零構建一個極簡 MVC 框架,代碼不足 200 行,卻包含完整請求生命週期。

目錄結構

mini-mvc/
├── public/              # Web 根目錄 (唯一入口)
│   └── index.php        # 入口文件
├── app/
│   ├── controllers/     # 控制器
│   ├── models/          # 模型
│   └── views/           # 視圖模板
├── core/                # 框架核心類
│   ├── Application.php  # 應用核心類
│   ├── Controller.php   # 控制器基類
│   ├── Model.php        # 模型基類
│   ├── View.php         # 視圖引擎
│   ├── Router.php       # 路由器
│   └── Request.php      # 請求封裝
├── config/              # 配置文件
│   └── database.php
└── vendor/              # Composer 依賴 (自動載入)

核心類實現

1. 入口文件 public/index.php

<?php
// 1. 定義常量
define('ROOT_PATH', dirname(__DIR__));
define('APP_PATH', ROOT_PATH . '/app');
define('CORE_PATH', ROOT_PATH . '/core');

// 2. 載入 Composer 自動載入
require_once ROOT_PATH . '/vendor/autoload.php';

// 3. 載入配置
$config = require ROOT_PATH . '/config/database.php';

// 4. 實例化應用核心並運行
$app = new Core\Application($config);
$app->run();
?>

2. 應用核心類 core/Application.php

<?php
namespace Core;

class Application {
    public Router $router;
    public Request $request;
    public Response $response;
    public View $view;
    public array $config;
    public ?Controller $controller = null;
    
    public function __construct(array $config) {
        $this->config = $config;
        $this->request = new Request();
        $this->response = new Response();
        $this->router = new Router($this->request);
        $this->view = new View(APP_PATH . '/views');
        
        // 註冊核心服務
        $this->registerServices();
    }
    
    private function registerServices(): void {
        // 數據庫連接 (單例)
        $this->db = new \PDO(
            "mysql:host={$this->config['host']};dbname={$this->config['dbname']};charset=utf8mb4",
            $this->config['user'],
            $this->config['pass'],
            [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]
        );
    }
    
    public function run(): void {
        try {
            // 1. 路由匹配
            $route = $this->router->resolve();
            
            // 2. 實例化控制器
            $controllerClass = $route['controller'];
            $this->controller = new $controllerClass($this);
            
            // 3. 執行動作方法
            $action = $route['action'];
            $params = $route['params'] ?? [];
            $content = call_user_func_array([$this->controller, $action], $params);
            
            // 4. 響應輸出
            if ($content !== null) {
                $this->response->setContent($content);
            }
            $this->response->send();
        } catch (\Throwable $e) {
            $this->handleException($e);
        }
    }
    
    private function handleException(\Throwable $e): void {
        http_response_code(500);
        if ($this->config['debug'] ?? false) {
            echo "<h1>{$e->getMessage()}</h1><pre>{$e->getTraceAsString()}</pre>";
        } else {
            echo $this->view->render('errors/500', ['message' => '服務器內部錯誤']);
        }
    }
    
    // 服務定位器模式
    public function __get(string $name) {
        if ($name === 'db') return $this->db;
        throw new \Exception("Service '$name' not found");
    }
}
?>

3. 路由器 core/Router.php

<?php
namespace Core;

class Router {
    private Request $request;
    private array $routes = [];
    
    public function __construct(Request $request) {
        $this->request = $request;
    }
    
    public function get(string $path, string $controller, string $action): self {
        $this->routes['GET'][$path] = compact('controller', 'action');
        return $this;
    }
    
    public function post(string $path, string $controller, string $action): self {
        $this->routes['POST'][$path] = compact('controller', 'action');
        return $this;
    }
    
    public function resolve(): array {
        $method = $this->request->getMethod();
        $uri = $this->request->getUri(); // 不含查詢字符串
        
        // 1. 精確匹配
        if (isset($this->routes[$method][$uri])) {
            return $this->routes[$method][$uri] + ['params' => []];
        }
        
        // 2. 參數路由匹配 /user/{id:\d+}
        foreach ($this->routes[$method] ?? [] as $pattern => $route) {
            $regex = '#^' . preg_replace('/\{(\w+)(?::([^}]+))?\}/', '(?P<$1>$2)', $pattern) . '$#';
            if (preg_match($regex, $uri, $matches)) {
                $params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
                return $route + ['params' => $params];
            }
        }
        
        // 3. 404
        throw new \Exception('Route not found: ' . $method . ' ' . $uri, 404);
    }
}
?>

4. 請求/響應封裝

<?php
namespace Core;

class Request {
    public function getMethod(): string {
        return $_SERVER['REQUEST_METHOD'];
    }
    
    public function getUri(): string {
        $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        return rtrim($uri, '/') ?: '/';
    }
    
    public function input(string $key, $default = null) {
        return $_POST[$key] ?? $_GET[$key] ?? $default;
    }
    
    public function all(): array {
        return array_merge($_GET, $_POST);
    }
}

class Response {
    private string $content = '';
    private int $statusCode = 200;
    private array $headers = ['Content-Type' => 'text/html; charset=utf-8'];
    
    public function setContent(string $content): self {
        $this->content = $content;
        return $this;
    }
    
    public function setStatusCode(int $code): self {
        $this->statusCode = $code;
        return $this;
    }
    
    public function header(string $name, string $value): self {
        $this->headers[$name] = $value;
        return $this;
    }
    
    public function json(mixed $data, int $status = 200): self {
        $this->header('Content-Type', 'application/json');
        $this->statusCode = $status;
        $this->content = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        return $this;
    }
    
    public function send(): void {
        http_response_code($this->statusCode);
        foreach ($this->headers as $name => $value) {
            header("$name: $value");
        }
        echo $this->content;
    }
}
?>

5. 控制器基類 core/Controller.php

<?php
namespace Core;

abstract class Controller {
    protected Application $app;
    protected View $view;
    protected Request $request;
    protected Response $response;
    protected \PDO $db;
    
    public function __construct(Application $app) {
        $this->app = $app;
        $this->view = $app->view;
        $this->request = $app->request;
        $this->response = $app->response;
        $this->db = $app->db;
    }
    
    // 快捷視圖渲染
    protected function render(string $view, array $data = []): string {
        return $this->view->render($view, $data);
    }
    
    // 快捷 JSON 響應
    protected function json(mixed $data, int $status = 200): Response {
        return $this->response->json($data, $status);
    }
    
    // 重定向
    protected function redirect(string $url, int $status = 302): Response {
        return $this->response->header('Location', $url)->setStatusCode($status);
    }
}
?>

6. 視圖引擎 core/View.php (原生 PHP 模板)

<?php
namespace Core;

class View {
    private string $viewsDir;
    private array $globals = [];
    
    public function __construct(string $viewsDir) {
        $this->viewsDir = rtrim($viewsDir, '/');
    }
    
    public function share(string $key, mixed $value): self {
        $this->globals[$key] = $value;
        return $this;
    }
    
    public function render(string $view, array $data = []): string {
        $file = $this->viewsDir . '/' . str_replace('.', '/', $view) . '.php';
        if (!file_exists($file)) {
            throw new \Exception("View not found: $file");
        }
        
        // 合併全局數據與局部數據
        $data = array_merge($this->globals, $data);
        
        // 提取變量到當前作用域
        extract($data, EXTR_SKIP);
        
        // 捕獲輸出
        ob_start();
        include $file;
        return ob_get_clean();
    }
}
?>

7. 模型基類 core/Model.php

<?php
namespace Core;

abstract class Model {
    protected \PDO $db;
    protected string $table;
    protected string $primaryKey = 'id';
    protected array $fillable = [];
    protected array $casts = [];
    
    public function __construct(\PDO $db) {
        $this->db = $db;
    }
    
    public function find(int $id): ?array {
        $stmt = $this->db->prepare("SELECT * FROM {$this->table} WHERE {$this->primaryKey} = ?");
        $stmt->execute([$id]);
        return $stmt->fetch() ?: null;
    }
    
    public function all(array $columns = ['*']): array {
        $cols = implode(', ', $columns);
        return $this->db->query("SELECT $cols FROM {$this->table}")->fetchAll();
    }
    
    public function create(array $data): int {
        $fields = [];
        $placeholders = [];
        $values = [];
        foreach ($data as $key => $val) {
            if (in_array($key, $this->fillable)) {
                $fields[] = "`$key`";
                $placeholders[] = "?";
                $values[] = $val;
            }
        }
        $sql = "INSERT INTO {$this->table} (" . implode(', ', $fields) . ") VALUES (" . implode(', ', $placeholders) . ")";
        $stmt = $this->db->prepare($sql);
        $stmt->execute($values);
        return (int)$this->db->lastInsertId();
    }
    
    // ... update, delete, query builder 方法可繼續擴展
}
?>

使用示例

路由定義 public/index.php (續)

<?php
// ... 前面代碼 ...
$app->router
    ->get('/', 'App\Controllers\HomeController', 'index')
    ->get('/post/{id:\d+}', 'App\Controllers\PostController', 'show')
    ->post('/post', 'App\Controllers\PostController', 'store');
$app->run();
?>

控制器 app/controllers/HomeController.php

<?php
namespace App\Controllers;

use Core\Controller;

class HomeController extends Controller {
    public function index(): string {
        $posts = $this->db->query("SELECT * FROM posts ORDER BY created_at DESC LIMIT 10")->fetchAll();
        return $this->render('home/index', ['posts' => $posts]);
    }
}
?>

視圖 app/views/home/index.php

<!DOCTYPE html>
<html>
<head><title>首頁</title></head>
<body>
    <h1>最新文章</h1>
    <ul>
    <?php foreach ($posts as $post): ?>
        <li><a href="/post/<?= $post['id'] ?>"><?= htmlspecialchars($post['title']) ?></a></li>
    <?php endforeach; ?>
    </ul>
</body>
</html>

擴展方向:生產級框架特性

特性實現方向
依賴注入容器實現 ContainerInterface (PSR-11),支援自動裝配、單例、工廠
中間件管道請求進入控制器前/後執行中間件 (認證、日誌、CORS、限流)
ORM / Query Builder整合 Eloquent、Doctrine DBAL 或自建 Fluent Builder
模板引擎Blade、Twig、Lathe,支援繼承、區塊、組件
驗證器表單請求驗證類、規則復用、錯誤消息國際化
事件/監聽器解耦業務邏輯,支援異步隊列
緩存抽象統一 Redis/Memcached/文件/數據庫驅動
測試支援PHPUnit 整合、HTTP 測試、數據庫遷移測試

總結

這個微型框架展示了 MVC 的骨架:

  1. 單一入口:public/index.php 接管所有請求。
  2. 路由分發:將 URI 映射到 Controller@action。
  3. 控制器協調:接收請求、調用模型、選擇視圖。
  4. 模型封裝:數據訪問邏輯、業務規則。
  5. 視圖渲染:模板文件 + 數據 = HTML 響應。

理解這個流程,再看 Laravel 的 Kernel、Router、Controller、Eloquent、Blade 就不再是黑盒,而是清晰可控的組件。

copyright © 萬盛學電腦網 all rights reserved