所有 HTTP 請求統一導向單一 PHP 檔案(通常是 index.php),由該檔案根據路由參數分派至對應處理邏輯。
| 模式 | URL 範例 | 入口檔案 |
|---|---|---|
| 多入口 | /news.php、/news_edit.php | 多個 PHP 檔案 |
| 單一入口 | /index.php?action=news、/index.php?action=edit | 單一 index.php |
index.php 實質上是「第二層路由解析」:Web Server 解析檔案路徑 → PHP 解析業務路由。
生產級分派器架構
run();核心邏輯封裝在
Application類別:
mod_rewrite 或 Nginx try_files 實現 /news/123 美觀網址事實:入口檔案應極簡(< 20 行),核心邏輯委派給框架核心類別。複雜度在架構設計,不在入口檔案。
// 原始:index.php?module=news&action=detail&id=123
// 解決方案:
// 1. URL 重寫
// Apache .htaccess:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
// 2. PATH_INFO 模式
// index.php/news/detail/123
// $_SERVER['PATH_INFO'] = '/news/detail/123'
入口檔案掛掉 = 全站掛掉。緩解:極簡入口、完善錯誤處理、健康檢查端點、多層快取。
app/ ├── modules/ │ ├── news/ │ │ ├── list.php │ │ ├── detail.php │ │ └── edit.php │ └── user/ │ ├── login.php │ └── register.php
優點:團隊協作無衝突。缺點:共用邏輯需額外 include。
// app/modules/News.php
class NewsModule {
public function list() { ... }
public function detail($id) { ... }
public function edit($id) { ... }
private function getCategories() { ... } // 共用邏輯
}
優點:共用邏輯自然封裝、自動載入友善。缺點:需版本控制解決衝突。
| 框架 | 入口檔案 | 核心分派類別 | 路由定義 |
|---|---|---|---|
| Laravel | public/index.php | Kernel / Router | routes/web.php |
| Symfony | public/index.php | Kernel / HttpKernel | config/routes.yaml |
| ThinkPHP | public/index.php | App / Dispatch | route/route.php |
| CodeIgniter 4 | public/index.php | CodeIgniter / Router | app/Config/Routes.php |
高流量公開頁(新聞列表、文章詳情)使用靜態化/獨立入口利於 SEO;互動功能(登入、發文、API)使用單一入口利於安全與維護。
單一入口模式不是銀彈,但它是現代 PHP 應用架構的基石。理解其核心——Dispatcher 的職責邊界、路由解析策略、中介軟體管線設計——才能駕馭各大框架,甚至自建輕量架構。