萬盛學電腦網

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

PHP 實作最簡單 MVC 框架教學:從零建立核心架構

MVC 模式核心概念

MVC (Model-View-Controller) 將應用程式分為三大核心組件:

  • Model (模型):資料層,負責資料庫操作、業務邏輯、資料驗證
  • View (視圖):表現層,負責 HTML 模板渲染、資料顯示
  • Controller (控制器):控制層,接收請求、協調 Model 與 View、回應結果

流程:請求 → 控制器 → 模型 (資料) → 控制器 → 視圖 (顯示) → 回應

極簡 MVC 目錄結構

simple-mvc/
├── index.php           # 單一入口點
├── config/
│   └── database.php    # 資料庫設定
├── core/               # 框架核心類別
│   ├── Controller.php  # 控制器基類
│   ├── Model.php       # 模型基類
│   ├── View.php        # 視圖基類
│   └── App.php         # 應用程式核心 (路由、分發)
├── app/
│   ├── controllers/    # 應用控制器
│   ├── models/         # 應用模型
│   └── views/          # 應用視圖
└── public/             # 公開資源 (CSS, JS, 圖片)
    └── index.php       # 實際入口 (生產環境)

核心基類實作

1. Model 基類 (資料庫操作封裝)

<?php
// core/Model.php
namespace Core;

use PDO;
use PDOException;

abstract class Model
{
    protected $pdo;
    protected $table;
    protected $primaryKey = 'id';
    
    public function __construct()
    {
        $config = require __DIR__ . '/../config/database.php';
        $dsn = "mysql:host={$config['host']};dbname={$config['dbname']};charset={$config['charset']}";
        $options = [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
        ];
        try {
            $this->pdo = new PDO($dsn, $config['user'], $config['pass'], $options);
        } catch (PDOException $e) {
            die("資料庫連線失敗: " . $e->getMessage());
        }
    }
    
    // 查詢所有
    public function all()
    {
        $stmt = $this->pdo->query("SELECT * FROM {$this->table}");
        return $stmt->fetchAll();
    }
    
    // 依主鍵查詢單筆
    public function find($id)
    {
        $stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE {$this->primaryKey} = ?");
        $stmt->execute([$id]);
        return $stmt->fetch();
    }
    
    // 新增
    public function create(array $data)
    {
        $fields = implode(', ', array_keys($data));
        $placeholders = ':' . implode(', :', array_keys($data));
        $sql = "INSERT INTO {$this->table} ($fields) VALUES ($placeholders)";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($data);
        return $this->pdo->lastInsertId();
    }
    
    // 更新
    public function update($id, array $data)
    {
        $set = implode(', ', array_map(fn($k) => "$k = :$k", array_keys($data)));
        $sql = "UPDATE {$this->table} SET $set WHERE {$this->primaryKey} = :id";
        $data['id'] = $id;
        $stmt = $this->pdo->prepare($sql);
        return $stmt->execute($data);
    }
    
    // 刪除
    public function delete($id)
    {
        $stmt = $this->pdo->prepare("DELETE FROM {$this->table} WHERE {$this->primaryKey} = ?");
        return $stmt->execute([$id]);
    }
    
    // 自訂查詢
    public function query($sql, $params = [])
    {
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll();
    }
}

2. View 基類 (模板渲染)

<?php
// core/View.php
namespace Core;

class View
{
    protected $viewPath;
    protected $data = [];
    
    public function __construct($viewPath = null)
    {
        $this->viewPath = $viewPath ?? __DIR__ . '/../../app/views/';
    }
    
    // 分配變數
    public function assign($key, $value = null)
    {
        if (is_array($key)) {
            $this->data = array_merge($this->data, $key);
        } else {
            $this->data[$key] = $value;
        }
    }
    
    // 渲染模板
    public function render($template, $data = [])
    {
        $this->assign($data);
        extract($this->data); // 變數解壓到當前作用域
        
        $file = $this->viewPath . $template . '.php';
        if (!file_exists($file)) {
            throw new \Exception("模板不存在: $file");
        }
        
        ob_start();
        include $file;
        return ob_get_clean();
    }
    
    // 直接輸出
    public function display($template, $data = [])
    {
        echo $this->render($template, $data);
    }
}

3. Controller 基類

<?php
// core/Controller.php
namespace Core;

abstract class Controller
{
    protected $view;
    
    public function __construct()
    {
        $this->view = new View();
    }
    
    // 載入模型
    protected function model($name)
    {
        $class = "App\\Models\\{$name}Model";
        if (class_exists($class)) {
            return new $class();
        }
        throw new \Exception("模型不存在: $class");
    }
    
    // 載入視圖
    protected function view($template, $data = [])
    {
        $this->view->display($template, $data);
    }
    
    // 重導向
    protected function redirect($url)
    {
        header("Location: $url");
        exit;
    }
}

4. App 核心分發器 (路由解析)

<?php
// core/App.php
namespace Core;

class App
{
    protected $controller = 'Home';
    protected $method = 'index';
    protected $params = [];
    
    public function __construct()
    {
        $this->parseUrl();
        $this->dispatch();
    }
    
    protected function parseUrl()
    {
        // PATHINFO 模式: /controller/method/param1/value1/...
        $uri = $_SERVER['REQUEST_URI'];
        $path = parse_url($uri, PHP_URL_PATH);
        $path = trim($path, '/');
        
        if ($path === '') {
            return; // 使用預設 Home/index
        }
        
        $segments = explode('/', $path);
        $this->controller = ucfirst(array_shift($segments)) . 'Controller';
        $this->method = array_shift($segments) ?: 'index';
        $this->params = $segments; // 剩餘為參數陣列
    }
    
    protected function dispatch()
    {
        $controllerClass = "App\\Controllers\\{$this->controller}";
        
        if (!class_exists($controllerClass)) {
            $this->error404("控制器不存在: {$this->controller}");
        }
        
        $controller = new $controllerClass();
        
        if (!method_exists($controller, $this->method)) {
            $this->error404("方法不存在: {$this->method}");
        }
        
        // 呼叫控制器方法,傳入參數
        call_user_func_array([$controller, $this->method], $this->params);
    }
    
    protected function error404($msg)
    {
        http_response_code(404);
        echo "

404 Not Found

$msg

"; exit; } }

應用層實作範例

資料庫設定

<?php
// config/database.php
return [
    'host' => 'localhost',
    'dbname' => 'test_db',
    'user' => 'root',
    'pass' => '',
    'charset' => 'utf8mb4',
];

模型:UserModel

<?php
// app/models/UserModel.php
namespace App\Models;
use Core\Model;

class UserModel extends Model
{
    protected $table = 'users';
}

控制器:UserController

<?php
// app/controllers/UserController.php
namespace App\Controllers;
use Core\Controller;

class UserController extends Controller
{
    public function index()
    {
        $userModel = $this->model('User');
        $users = $userModel->all();
        $this->view('user/index', ['users' => $users]);
    }
    
    public function show($id)
    {
        $userModel = $this->model('User');
        $user = $userModel->find($id);
        if (!$user) {
            $this->error404("使用者不存在: $id");
        }
        $this->view('user/show', ['user' => $user]);
    }
    
    public function create()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $userModel = $this->model('User');
            $id = $userModel->create($_POST);
            $this->redirect("/user/show/$id");
        }
        $this->view('user/create');
    }
}

視圖:user/index.php

<!-- app/views/user/index.php -->
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>使用者列表</title>
</head>
<body>
    <h1>使用者列表</h1>
    <a href="/user/create">新增使用者</a>
    <table border="1">
        <tr><th>ID</th><th>名稱</th><th>Email</th><th>操作</th></tr>
        <?php foreach ($users as $user): ?>
        <tr>
            <td><?= $user['id'] ?></td>
            <td><?= htmlspecialchars($user['name']) ?></td>
            <td><?= htmlspecialchars($user['email']) ?></td>
            <td>
                <a href="/user/show/<?= $user['id'] ?>">查看</a>
            </td>
        </tr>
        <?php endforeach; ?>
    </table>
</body>
</html>

入口檔案

<?php
// public/index.php (生產環境入口)
define('APP_ROOT', __DIR__ . '/..');
require_once APP_ROOT . '/vendor/autoload.php'; // 或手動 require 核心檔案

// 簡易自動載入 (無 Composer 時)
spl_autoload_register(function ($class) {
    $file = APP_ROOT . '/' . str_replace('\\', '/', $class) . '.php';
    if (file_exists($file)) require_once $file;
});

new Core\App();

.htaccess (Apache) / Nginx 設定

# Apache .htaccess (放在 public/ 目錄)
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

# Nginx
location / {
    try_files $uri $uri/ /index.php?$query_string;
}

擴充方向 (真實專案需求)

  • 路由系統:支援 RESTful、命名路由、路由群組、中介軟體
  • 請求/回應物件:封裝 $_GET, $_POST, Header, Cookie, JSON 輸出
  • 驗證器:表單驗證、規則複用
  • 資料庫遷移:版本控制資料庫結構
  • 依賴注入容器:解耦合、方便測試
  • 錯誤/例外處理:統一錯誤頁面、日誌記錄
  • 快取/Session/認證/授權:完整應用基礎設施

結語

這個極簡 MVC 框架展示了核心架構:單一入口、路由分發、控制器協調、模型操作資料、視圖渲染輸出。雖然功能精簡,但已具備現代 PHP 框架的靈魂。理解此運作原理,再學習 Laravel、ThinkPHP、Symfony 等成熟框架時將更得心應手。

copyright © 萬盛學電腦網 all rights reserved