所有 PHP 框架的入口都是同一个 index.php:Nginx 把所有请求转发给它,它在内部决定调用哪段代码。自己写一遍,再用框架就不迷糊了。
Nginx 配置
location / {
try_files $uri $uri/ /index.php?$query_string;
}文件存在就直接返回(静态资源),不存在就交给 index.php。这就是「单入口」的全部秘密。
路由表与匹配
<?php
// index.php
require __DIR__ . '/app.php';
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$path = rtrim($path, '/') ?: '/';
$routes = [
'GET' => [
'/' => ['HomeController', 'index'],
'/article' => ['ArticleController', 'index'],
],
'POST' => [
'/article' => ['ArticleController', 'store'],
],
];
$method = $_SERVER['REQUEST_METHOD'];
$handler = $routes[$method][$path] ?? null;
if ($handler === null) {
http_response_code(404);
require __DIR__ . '/views/404.php';
exit;
}
[$class, $action] = $handler;
require __DIR__ . '/controllers/' . $class . '.php';
(new $class())->$action();路由表把「方法 + 路径」映射到「类 + 方法」。带参数的路由需要正则匹配,比如 /article/(\d+)。
带参数的路由
foreach ($routes[$method] as $pattern => $h) {
if (preg_match('#^' . $pattern . '$#', $path, $m)) {
array_shift($m);
[$class, $action] = $h;
(new $class())->$action(...$m);
exit;
}
}把路由写成 /article/(\d+) 这样的正则,匹配到的捕获组作为参数传给方法。注意路由要先匹配具体的,再匹配通配的,否则 /\.+ 会吃掉所有路径。
控制器与视图
控制器只做三件事:取参数、调业务、选视图。业务逻辑放在 service 里,控制器保持薄。视图就是一个 PHP 文件,用 extract 把数据变成变量。
class ArticleController
{
public function index(): void
{
$page = max(1, (int)($_GET['page'] ?? 1));
$articles = (new ArticleService())->paginate($page, 20);
view('article/index', ['articles' => $articles, 'page' => $page]);
}
}
function view(string $tpl, array $data = []): void
{
extract($data, EXTR_SKIP);
require __DIR__ . '/views/' . $tpl . '.php';
}extract 会把数组键变成变量,注意不要和已有变量重名,EXTR_SKIP 可以避免覆盖。视图里输出变量记得 htmlspecialchars。
这个骨架不到一百行,但已经具备路由、控制器、视图三件套。看懂它,再去看 Laravel 的路由文件就不会觉得神秘了。