mvc-demo/
├─ index.php # 入口
├─ Controller/
│ └─ TestController.php
├─ Model/
│ └─ TestModel.php
├─ View/
│ └─ TestView.php
<?php
// Model/TestModel.php
class TestModel {
public function getMessage(): string {
// 實際專案這裡會查資料庫
return "Hello from Model at " . date('Y-m-d H:i:s');
}
}
<?php
// View/TestView.php
class TestView {
public function render(string $data): void {
// 簡單輸出,實際會 include 模板檔
echo "View Output
";
echo "{$data}
";
}
}
<?php
// Controller/TestController.php
require_once __DIR__ . '/../Model/TestModel.php';
require_once __DIR__ . '/../View/TestView.php';
class TestController {
public function show(): void {
// 1. 選擇模型
$model = new TestModel();
// 2. 取得資料
$data = $model->getMessage();
// 3. 選擇視圖
$view = new TestView();
// 4. 渲染輸出
$view->render($data);
}
}
<?php
// index.php
require_once __DIR__ . '/Controller/TestController.php';
$controller = new TestController();
$controller->show();
瀏覽 https://localhost/mvc-demo/ 顯示:
View Output
Hello from Model at 2024-01-15 14:30:00
<?php
// index.php 升級版
spl_autoload_register(function ($class) {
$file = __DIR__ . '/' . str_replace('\\', '/', $class) . '.php';
if (file_exists($file)) require_once $file;
});
// 簡單路由:?c=Test&a=show
$controllerName = ($_GET['c'] ?? 'Test') . 'Controller';
$action = $_GET['a'] ?? 'show';
$class = "Controller\\{$controllerName}";
if (class_exists($class)) {
$controller = new $class();
if (method_exists($controller, $action)) {
$controller->$action();
} else {
http_response_code(404);
echo "Action {$action} not found";
}
} else {
http_response_code(404);
echo "Controller {$controllerName} not found";
}
| 特性 | 本教學極簡版 | 現代框架 |
|---|---|---|
| 依賴管理 | require_once | Composer + PSR-4 自動載入 |
| 路由 | 手動 $_GET | 路由集合、中介軟體、屬性路由 |
| 模型 | 純類別 | ORM、Repository、Entity、遷移 |
| 視圖 | echo 字串 | 模板引擎、佈局、元件、資料綁定 |
| 請求/回應 | 超全域變數 | PSR-7 Request/Response 物件 |
| 依賴注入 | new 硬編碼 | 容器、自動配線、介面綁定 |