萬盛學電腦網

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

從零打造輕量 PHP MVC 框架:核心元件與自動載入實作

設計目標

理解框架核心運作:路由分發、自動載入、控制器/模型基底、視圖渲染。掌握後,學習 Laravel/ThinkPHP 等主流框架將事半功倍。

目錄結構

app/
├── core/           # 核心類別
│   ├── Base.php        # 抽象基底
│   ├── Controller.php  # 控制器基底
│   ├── Model.php       # 模型基底
│   └── Router.php      # 路由分發
├── controllers/    # 業務控制器
├── models/         # 資料模型
├── views/          # 視圖模板
└── public/
    └── index.php   # 統一入口

核心類別實作

1. 自動載入

<?php
// core/Autoload.php
spl_autoload_register(function ($class) {
    $paths = [
        __DIR__ . '/../controllers/',
        __DIR__ . '/../models/',
        __DIR__ . '/'
    ];
    foreach ($paths as $path) {
        $file = $path . $class . '.php';
        if (file_exists($file)) {
            require_once $file;
            return;
        }
    }
});

2. 抽象基底類別

<?php
// core/Base.php
abstract class Base {
    protected $db;
    public function __construct(PDO $db) {
        $this->db = $db;
    }
}

3. 模型基底

<?php
// core/Model.php
abstract class Model extends Base {
    protected $table;
    public function all(): array {
        return $this->db->query("SELECT * FROM {$this->table}")->fetchAll();
    }
    public function find(int $id): ?array {
        $stmt = $this->db->prepare("SELECT * FROM {$this->table} WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch() ?: null;
    }
}

4. 控制器基底與視圖渲染

<?php
// core/Controller.php
abstract class Controller extends Base {
    protected function view(string $template, array $data = []): void {
        extract($data);
        include __DIR__ . "/../views/{$template}.phtml";
    }
    abstract public function index();
}

5. 路由分發器

<?php
// core/Router.php
class Router {
    public function dispatch(string $uri): void {
        // 簡易解析 /controller/action/params
        $parts = array_values(array_filter(explode('/', trim($uri, '/'))));
        $controllerName = ucfirst($parts[0] ?? 'Index') . 'Controller';
        $action = $parts[1] ?? 'index';
        $params = array_slice($parts, 2);

        $file = __DIR__ . "/../controllers/{$controllerName}.php";
        if (!file_exists($file)) {
            http_response_code(404);
            exit('Controller not found');
        }
        require_once $file;
        if (!class_exists($controllerName)) {
            http_response_code(500);
            exit('Class missing');
        }
        $controller = new $controllerName($GLOBALS['db']);
        if (!method_exists($controller, $action)) {
            http_response_code(404);
            exit('Action not found');
        }
        call_user_func_array([$controller, $action], $params);
    }
}

入口檔案

<?php
// public/index.php
define('APP_ROOT', dirname(__DIR__));
require APP_ROOT . '/app/core/Autoload.php';

// 資料庫連線(單例)
$GLOBALS['db'] = new PDO('mysql:host=127.0.0.1;dbname=test;charset=utf8', 'root', '');

// 分發請求
$router = new Router();
$router->dispatch($_SERVER['REQUEST_URI']);

擴充範例:UserController

<?php
// app/controllers/UserController.php
class UserController extends Controller {
    public function index() {
        $users = $this->model->all(); // 假設注入 UserModel
        $this->view('user/list', ['users' => $users]);
    }
    public function show($id) {
        $user = $this->model->find((int)$id);
        $this->view('user/show', ['user' => $user]);
    }
}

總結與擴充方向

  • 依賴注入容器:解耦 Controller 與 Model 建立
  • 中介層:認證、CSRF、日誌、限流
  • 視圖引擎:整合 Blade/Twig/Plates
  • 資料庫遷移與 Seeder
  • RESTful 資源路由、API 版本控制

此極簡框架約 100 行核心代碼,展現 MVC 本質。實務專案建議直接採用成熟框架,專注業務邏輯開發。

copyright © 萬盛學電腦網 all rights reserved