動手實作前,請確保掌握以下基礎:
index.php (單一入口)
↓
Init.php (核心初始化:常數定義、自動載入、配置載入)
↓
Core/Controller.php (核心控制器:路由解析、控制器實例化、動作分發)
↓
Controllers/Welcome.php (業務控制器範例)
↓
Core/View.php / Core/Model.php (視圖與模型基礎類)
public/index.php<?php
// 定義專案根目錄
define('ROOT_PATH', __DIR__ . '/../');
// 載入 Composer 自動載入器
require ROOT_PATH . 'vendor/autoload.php';
// 引導應用程式
$app = new \Core\Application();
$app->run();
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)
];
}
}
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();
}
}
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;
}
}
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)
]);
}
}
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>
這個極簡 MVC 框架展示了核心概念:單一入口 → 路由解析 → 控制器分發 → 模型處理資料 → 視圖輸出回應。雖然功能精簡,但架構清晰,易於理解與擴充。實際專案建議採用成熟框架(Laravel、Symfony、ThinkPHP),但手寫框架過程能深入理解框架運作原理,為進階開發打下堅實基礎。