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

從零手寫 PHP 簡易 MVC 框架:核心架構與執行流程深度解析

     編輯:PHP 綜合知識

前置知識準備

動手實作前,請確保掌握以下基礎:

  • PHP 物件導向程式設計(類、介面、繼承、命名空間)
  • 單一入口模式原理(參考:單一入口應用程式分析)
  • Composer 自動載入(PSR-4 標準)

整體架構圖解

index.php (單一入口)
    ↓
Init.php (核心初始化:常數定義、自動載入、配置載入)
    ↓
Core/Controller.php (核心控制器:路由解析、控制器實例化、動作分發)
    ↓
Controllers/Welcome.php (業務控制器範例)
    ↓
Core/View.php / Core/Model.php (視圖與模型基礎類)

核心程式碼實作

1. 入口檔案 public/index.php

<?php
// 定義專案根目錄
define('ROOT_PATH', __DIR__ . '/../');

// 載入 Composer 自動載入器
require ROOT_PATH . 'vendor/autoload.php';

// 引導應用程式
$app = new \Core\Application();
$app->run();

2. 應用程式核心類 Core/Application.php

<?php
namespace Core;

class Application
{
    protected $config = [];
    
    public function __construct()
    {
        $this->loadConfig();
        $this->setupAutoload();
    }
    
    protected function loadConfig()
    {
        $this->config = require ROOT_PATH . 'config/app.php';
    }
    
    protected function setupAutoload()
    {
        spl_autoload_register(function ($class) {
            $file = ROOT_PATH . str_replace('\\', '/', $class) . '.php';
            if (file_exists($file)) {
                require $file;
            }
        });
    }
    
    public function run()
    {
        // 解析路由
        $route = $this->parseRoute();
        
        // 實例化控制器並執行動作
        $controllerClass = '\\Controllers\\' . ucfirst($route['controller']) . 'Controller';
        if (!class_exists($controllerClass)) {
            throw new \Exception("控制器不存在: {$controllerClass}");
        }
        
        $controller = new $controllerClass();
        $action = $route['action'] . 'Action';
        
        if (!method_exists($controller, $action)) {
            throw new \Exception("動作不存在: {$action}");
        }
        
        return $controller->$action();
    }
    
    protected function parseRoute()
    {
        // 簡易路由解析:/controller/action/params
        $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $uri = trim($uri, '/');
        
        $segments = $uri ? explode('/', $uri) : [];
        
        return [
            'controller' => $segments[0] ?? $this->config['default_controller'] ?? 'welcome',
            'action'     => $segments[1] ?? $this->config['default_action'] ?? 'index',
            'params'     => array_slice($segments, 2)
        ];
    }
}

3. 基礎控制器 Core/Controller.php

<?php
namespace Core;

abstract class Controller
{
    protected $view;
    
    public function __construct()
    {
        $this->view = new View();
    }
    
    protected function render($template, $data = [])
    {
        return $this->view->render($template, $data);
    }
    
    protected function model($name)
    {
        $class = '\\Models\\' . ucfirst($name) . 'Model';
        return new $class();
    }
}

4. 視圖類 Core/View.php

<?php
namespace Core;

class View
{
    protected $data = [];
    
    public function render($template, $data = [])
    {
        $this->data = array_merge($this->data, $data);
        extract($this->data);
        
        $file = ROOT_PATH . "views/{$template}.php";
        if (!file_exists($file)) {
            throw new \Exception("視圖檔案不存在: {$file}");
        }
        
        ob_start();
        include $file;
        return ob_get_clean();
    }
    
    public function assign($key, $value)
    {
        $this->data[$key] = $value;
    }
}

5. 範例控制器 Controllers/WelcomeController.php

<?php
namespace Controllers;

use Core\Controller;

class WelcomeController extends Controller
{
    public function indexAction()
    {
        return $this->render('welcome/index', [
            'title' => '歡迎來到自製 MVC 框架',
            'message' => 'Hello, MVC!'
        ]);
    }
    
    public function showAction($name = 'World')
    {
        return $this->render('welcome/show', [
            'name' => htmlspecialchars($name)
        ]);
    }
}

6. 範例視圖 views/welcome/index.php

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title><?= $title ?></title>
</head>
<body>
    <h1><?= $message ?></h1>
    <p>當前路由:welcome/index</p>
</body>
</html>

進階擴充方向

  1. 路由系統:支援 RESTful、參數綁定、中介軟體
  2. 資料庫抽象層:PDO 封裝、查詢建構器、ORM 基礎
  3. 依賴注入容器:管理服務實例、支援介面綁定
  4. 錯誤處理:例外捕獲、日誌記錄、友善錯誤頁面
  5. 快取機制:檔案/Redis/Memcached 多驅動支援

總結

這個極簡 MVC 框架展示了核心概念:單一入口 → 路由解析 → 控制器分發 → 模型處理資料 → 視圖輸出回應。雖然功能精簡,但架構清晰,易於理解與擴充。實際專案建議採用成熟框架(Laravel、Symfony、ThinkPHP),但手寫框架過程能深入理解框架運作原理,為進階開發打下堅實基礎。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved