理解框架核心運作:路由分發、自動載入、控制器/模型基底、視圖渲染。掌握後,學習 Laravel/ThinkPHP 等主流框架將事半功倍。
app/
├── core/ # 核心類別
│ ├── Base.php # 抽象基底
│ ├── Controller.php # 控制器基底
│ ├── Model.php # 模型基底
│ └── Router.php # 路由分發
├── controllers/ # 業務控制器
├── models/ # 資料模型
├── views/ # 視圖模板
└── public/
└── index.php # 統一入口
<?php
// core/Autoload.php
spl_autoload_register(function ($class) {
$paths = [
__DIR__ . '/../controllers/',
__DIR__ . '/../models/',
__DIR__ . '/'
];
foreach ($paths as $path) {
$file = $path . $class . '.php';
if (file_exists($file)) {
require_once $file;
return;
}
}
});
<?php
// core/Base.php
abstract class Base {
protected $db;
public function __construct(PDO $db) {
$this->db = $db;
}
}
<?php
// core/Model.php
abstract class Model extends Base {
protected $table;
public function all(): array {
return $this->db->query("SELECT * FROM {$this->table}")->fetchAll();
}
public function find(int $id): ?array {
$stmt = $this->db->prepare("SELECT * FROM {$this->table} WHERE id = ?");
$stmt->execute([$id]);
return $stmt->fetch() ?: null;
}
}
<?php
// core/Controller.php
abstract class Controller extends Base {
protected function view(string $template, array $data = []): void {
extract($data);
include __DIR__ . "/../views/{$template}.phtml";
}
abstract public function index();
}
<?php
// core/Router.php
class Router {
public function dispatch(string $uri): void {
// 簡易解析 /controller/action/params
$parts = array_values(array_filter(explode('/', trim($uri, '/'))));
$controllerName = ucfirst($parts[0] ?? 'Index') . 'Controller';
$action = $parts[1] ?? 'index';
$params = array_slice($parts, 2);
$file = __DIR__ . "/../controllers/{$controllerName}.php";
if (!file_exists($file)) {
http_response_code(404);
exit('Controller not found');
}
require_once $file;
if (!class_exists($controllerName)) {
http_response_code(500);
exit('Class missing');
}
$controller = new $controllerName($GLOBALS['db']);
if (!method_exists($controller, $action)) {
http_response_code(404);
exit('Action not found');
}
call_user_func_array([$controller, $action], $params);
}
}
<?php
// public/index.php
define('APP_ROOT', dirname(__DIR__));
require APP_ROOT . '/app/core/Autoload.php';
// 資料庫連線(單例)
$GLOBALS['db'] = new PDO('mysql:host=127.0.0.1;dbname=test;charset=utf8', 'root', '');
// 分發請求
$router = new Router();
$router->dispatch($_SERVER['REQUEST_URI']);
<?php
// app/controllers/UserController.php
class UserController extends Controller {
public function index() {
$users = $this->model->all(); // 假設注入 UserModel
$this->view('user/list', ['users' => $users]);
}
public function show($id) {
$user = $this->model->find((int)$id);
$this->view('user/show', ['user' => $user]);
}
}
此極簡框架約 100 行核心代碼,展現 MVC 本質。實務專案建議直接採用成熟框架,專注業務邏輯開發。