php路由实现
PHP 路由实现方法
基础路由实现
使用 $_SERVER['REQUEST_URI'] 解析请求路径,结合条件判断实现简单路由:
$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';
}
正则表达式路由
通过正则匹配实现动态路由参数提取:
preg_match('#^/user/(\d+)$#', $request, $matches);
if (!empty($matches)) {
$userId = $matches[1];
require 'user_profile.php';
}
面向对象路由类
创建可复用的路由类处理路由逻辑:
class Router {
private $routes = [];
public function addRoute($pattern, $handler) {
$this->routes[$pattern] = $handler;
}
public function dispatch() {
foreach ($this->routes as $pattern => $handler) {
if (preg_match($pattern, $this->request, $matches)) {
call_user_func($handler, $matches);
return;
}
}
// 404处理
}
}
使用第三方路由组件
常见PHP路由组件安装和使用示例:

composer require altorouter/altorouter
$router = new AltoRouter();
$router->map('GET', '/users', 'UserController#index');
$match = $router->match();
if ($match) {
call_user_func($match['target']);
}
RESTful API 路由
实现REST风格的路由配置:
$router->map('GET', '/api/users', 'getAllUsers');
$router->map('POST', '/api/users', 'createUser');
$router->map('PUT', '/api/users/[i:id]', 'updateUser');
路由缓存优化
对频繁访问的路由进行缓存处理:

if (file_exists('routes.cache')) {
$routes = unserialize(file_get_contents('routes.cache'));
} else {
// 生成路由配置
file_put_contents('routes.cache', serialize($routes));
}
中间件支持
在路由处理前后添加中间件逻辑:
$router->before('auth', function() {
if (!isLoggedIn()) {
redirect('/login');
}
});
$router->get('/dashboard', 'DashboardController@index', ['middleware' => 'auth']);
自动路由生成
根据控制器方法自动生成路由:
// 自动映射 Controller@method 形式
foreach (get_class_methods('UserController') as $method) {
$router->addRoute("/user/$method", "UserController@$method");
}
路由分组
实现具有共同前缀的路由分组:
$router->group('/admin', function($router) {
$router->get('/users', 'AdminController@users');
$router->get('/settings', 'AdminController@settings');
});






