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/
index.phpinclude("core/ini.php");
initializer::initialize();
$router = loader::load("router");
dispatcher::dispatch($router);
core/ini.php 設定 include_path 與 autoloadset_include_path(get_include_path() . PATH_SEPARATOR . "core/main");
function __autoload($class) { require_once("{$class}.php"); }
initializer.php 擴展 include_pathclass 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);
}
}
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];
}
}
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]。
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 即可看到輸出。