PHP实现路由的核心在于统一入口文件(如index.php),通过服务器重写规则拦截所有请求,解析REQUEST_URI路径,匹配HTTP方法与注册路由,支持静态与动态参数分发至对应控制器或回调函数。

PHP实现路由的核心在于拦截所有请求,统一入口,再根据URL路径分发到对应处理逻辑。最常见的做法是使用单一入口文件(如 index.php),结合服务器重写规则,将所有请求导向该文件,由PHP解析URI并调用相应控制器或回调函数。
1. 基础路由机制原理
一个基础的PHP路由系统包含以下几个关键点:
- 统一入口:所有请求都通过 index.php 处理,避免直接访问多个PHP文件。
- URL重写:利用Apache的.htaccess或Nginx配置,隐藏index.php,使URL更友好。
- 解析请求路径:从 $_SERVER['REQUEST_URI'] 中提取路径信息。
- 匹配与分发:将路径映射到对应的函数、类方法或控制器。
2. 简单路由实现示例
以下是一个轻量级的手动路由实现:
// index.php $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);if ($uri === '/user') { include 'controllers/user.php'; } elseif ($uri === '/post') { include 'controllers/post.php'; } elseif ($uri === '/') { echo "首页"; } else { http_response_code(404); echo "页面未找到"; }
这种方式适合小型项目,但扩展性差。可以进一步优化为数组注册式路由:
立即学习“PHP免费学习笔记(深入)”;
$routes = [
'GET /' => 'HomeController@index',
'GET /user' => 'UserController@list',
'POST /user' => 'UserController@create',
];
$method = $_SERVER['REQUEST_METHOD'];
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$key = "$method $path";
if (array_key_exists($key, $routes)) {
list($controller, $action) = explode('@', $routes[$key]);
require "controllers/$controller.php";
call_user_func([new $controller, $action]);
} else {
http_response_code(404);
echo "Not Found";
}
3. URL重写配置(.htaccess)
为了让路由生效,需配置服务器隐藏 index.php:
# .htaccess 文件(Apache)
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
Nginx 配置示例:
location / {
try_files $uri $uri/ /index.php?$query_string;
}
4. 支持动态参数的进阶路由
真实项目中常需要捕获变量,例如 /user/123:
$routes = [
'GET /user/(\d+)' => 'UserController@show',
];
foreach ($routes as $pattern => $handler) {
list($method, $pathPattern) = explode(' ', $pattern, 2);
if ($_SERVER['REQUEST_METHOD'] !== $method) continue;
$regex = '#^' . str_replace('/', '\/', $pathPattern) . '$#';
if (preg_match($regex, $uri, $matches)) {
array_shift($matches); // 移除全匹配
list($controller, $action) = explode('@', $handler);
require "controllers/$controller.php";
call_user_func_array([new $controller, $action], $matches);
exit;
}}
基本上就这些。简单项目可手动实现,复杂应用建议使用框架(如 Laravel、Slim)内置路由,功能更完整,支持中间件、命名路由、分组等高级特性。核心思想不变:统一入口 + 路径解析 + 分发执行。不复杂但容易忽略细节,比如HTTP方法区分和正则转义。











