php 路由实现
PHP 路由实现方法
在 PHP 中实现路由功能有多种方式,以下是几种常见的实现方法:
使用原生 PHP 实现
通过解析 URL 并匹配对应的控制器和动作:
$request = $_SERVER['REQUEST_URI'];
switch ($request) {
case '/':
require 'home.php';
break;
case '/about':
require 'about.php';
break;
default:
http_response_code(404);
require '404.php';
break;
}
使用正则表达式匹配路由
更灵活的路由匹配方式:
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$routes = [
'/^\/user\/(\d+)$/' => 'user.php',
'/^\/post\/([a-z0-9-]+)$/' => 'post.php'
];
foreach ($routes as $pattern => $file) {
if (preg_match($pattern, $uri, $matches)) {
require $file;
exit;
}
}
使用 Composer 包
流行的 PHP 路由组件:
-
安装 FastRoute:
composer require nikic/fast-route -
使用示例:
$dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) { $r->addRoute('GET', '/users', 'get_all_users_handler'); $r->addRoute('GET', '/user/{id:\d+}', 'get_user_handler'); });
$httpMethod = $_SERVER['REQUEST_METHOD']; $uri = $_SERVER['REQUEST_URI'];
#### 框架内置路由
主流 PHP 框架都提供了路由功能:
Laravel 路由示例:
```php
Route::get('/', function () {
return view('welcome');
});
Route::get('/user/{id}', function ($id) {
return 'User '.$id;
});
Symfony 路由示例:
// config/routes.yaml
index:
path: /
controller: App\Controller\DefaultController::index
RESTful API 路由
实现 RESTful 风格的路由:
$method = $_SERVER['REQUEST_METHOD'];
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
if ($method === 'GET' && $path === '/api/users') {
// 获取用户列表
} elseif ($method === 'POST' && $path === '/api/users') {
// 创建用户
}
路由参数处理
获取路由中的参数:
preg_match('/\/user\/(\d+)/', $uri, $matches);
$userId = $matches[1] ?? null;
中间件支持
在路由中添加中间件:
$router->get('/admin', function() {
// 管理员页面
})->middleware('auth');
选择哪种实现方式取决于项目需求,小型项目可以使用简单实现,大型项目建议使用成熟的框架或路由组件。







