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

從零構建簡易 PHP MVC 架構:單一入口、路由、分派器實作

     編輯:PHP 相關知識

MVC 三層分工:Model(數據存取)、View(視圖輸出)、Controller(業務邏輯與分派)。單一入口模式將所有請求導向 index.php,統一初始化、路由解析、控制器分派。

目錄結構

/
├── index.php          # 單一入口
├── core/
│   ├── ini.php        # 環境初始化、autoload
│   ├── main/
│   │   ├── initializer.php
│   │   ├── loader.php
│   │   ├── router.php
│   │   └── dispatcher.php
├── app/
│   ├── controllers/
│   ├── models/
│   └── views/

核心檔案

1. 入口 index.php

include("core/ini.php");
initializer::initialize();
$router = loader::load("router");
dispatcher::dispatch($router);

2. core/ini.php 設定 include_path 與 autoload

set_include_path(get_include_path() . PATH_SEPARATOR . "core/main");
function __autoload($class) { require_once("{$class}.php"); }

3. initializer.php 擴展 include_path

class initializer {
    public static function initialize() {
        $paths = ["core/main","core/main/cache","core/helpers","core/libraries",
                  "app/controllers","app/models","app/views"];
        foreach ($paths as $p) set_include_path(get_include_path().PATH_SEPARATOR.$p);
    }
}

4. loader.php 單例載入核心組件

class loader {
    private static $loaded = [];
    public static function load($object) {
        $valid = ["library","view","model","helper","router","config","hook","cache","db"];
        if (!in_array($object,$valid)) throw new Exception("Invalid component: $object");
        if (empty(self::$loaded[$object])) self::$loaded[$object] = new $object();
        return self::$loaded[$object];
    }
}

5. router.php 解析 URL 參數

class router {
    private $route, $controller, $action, $params;
    public function __construct() {
        $path = array_keys($_GET);
        $route = $path[0] ?? 'index';
        $this->route = $route;
        $parts = explode("/", $route);
        $this->controller = $parts[0];
        $this->action = $parts[1] ?? 'base';
        array_shift($parts); array_shift($parts);
        $this->params = $parts;
    }
    public function getController() { return $this->controller; }
    public function getAction() { return $this->action ?: 'main'; }
    public function getParams() { return $this->params; }
}

URL 範例:index.php?user/profile/id/3 → controller=user, action=profile, params=[id,3]。

6. dispatcher.php 分派執行

class dispatcher {
    public static function dispatch($router) {
        ob_start();
        $controller = $router->getController();
        $action = $router->getAction();
        $params = $router->getParams();
        $file = "app/controllers/{$controller}.php";
        if (file_exists($file)) {
            require_once($file);
            $app = new $controller();
            $app->setParams($params);
            $app->$action();
            $output = ob_get_clean();
            echo $output;
        } else throw new Exception("Controller not found: $controller");
    }
}

測試控制器

// app/controllers/user.php
class user {
    public function base() {}
    public function login() { echo 'login html page'; }
    public function register() { echo 'register html page'; }
    public function setParams($params){ var_dump($params); }
}

瀏覽器訪問 index.php?user/login 或 index.php?user/register 即可看到輸出。

擴展方向

  • 引入 View 類別渲染模板檔案。
  • Model 基類封裝資料庫操作。
  • 增加 Hook/Filter 機制、快取層、權限控制。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved