php实现路由
PHP 路由实现方法
在 PHP 中实现路由功能可以通过多种方式完成,以下是几种常见的方法:
1. 基于 .htaccess 和查询参数的路由
通过 Apache 的 mod_rewrite 模块将所有请求重定向到单一入口文件(如 index.php),然后解析 URL 路径决定调用哪个控制器和方法。
// .htaccess 文件内容
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
// index.php 文件
$url = isset($_GET['url']) ? $_GET['url'] : 'home';
$urlParts = explode('/', rtrim($url, '/'));
$controllerName = isset($urlParts[0]) ? $urlParts[0] : 'home';
$actionName = isset($urlParts[1]) ? $urlParts[1] : 'index';
2. 使用 FastRoute 库

FastRoute 是一个高性能的 PHP 路由库,适合现代 PHP 应用。
require 'vendor/autoload.php';
$dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) {
$r->addRoute('GET', '/users', 'UserController@index');
$r->addRoute('GET', '/user/{id:\d+}', 'UserController@show');
});
$httpMethod = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];
$routeInfo = $dispatcher->dispatch($httpMethod, $uri);
switch ($routeInfo[0]) {
case FastRoute\Dispatcher::FOUND:
$handler = $routeInfo[1];
$vars = $routeInfo[2];
// 调用对应的控制器和方法
break;
// 处理其他情况
}
3. Laravel 风格的路由实现

可以模仿 Laravel 的路由系统实现一个简化版:
class Router {
protected static $routes = [];
public static function get($uri, $action) {
self::$routes['GET'][$uri] = $action;
}
public static function post($uri, $action) {
self::$routes['POST'][$uri] = $action;
}
public static function dispatch() {
$method = $_SERVER['REQUEST_METHOD'];
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
if (isset(self::$routes[$method][$uri])) {
$action = self::$routes[$method][$uri];
if (is_callable($action)) {
$action();
} elseif (is_string($action)) {
list($controller, $method) = explode('@', $action);
(new $controller)->$method();
}
} else {
http_response_code(404);
echo '404 Not Found';
}
}
}
// 使用示例
Router::get('/', 'HomeController@index');
Router::post('/submit', 'FormController@submit');
Router::dispatch();
4. 使用 Symfony Routing 组件
Symfony 的路由组件可以单独使用,功能强大:
require 'vendor/autoload.php';
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
$routes = new RouteCollection();
$routes->add('home', new Route('/', [
'_controller' => 'HomeController::index'
]));
$routes->add('user_show', new Route('/user/{id}', [
'_controller' => 'UserController::show'
], ['id' => '\d+']));
$context = new RequestContext();
$context->fromRequest(Request::createFromGlobals());
$matcher = new UrlMatcher($routes, $context);
$parameters = $matcher->match($context->getPathInfo());
$controllerParts = explode('::', $parameters['_controller']);
$controller = new $controllerParts[0];
$controller->{$controllerParts[1]}($parameters);
路由实现注意事项
- 路由解析应考虑 URL 规范化,处理尾部斜杠等问题
- 需要实现 404 页面处理
- 对于动态参数路由,应支持参数约束
- 考虑路由缓存机制提升性能
- 支持路由分组和中间件功能
以上方法可以根据项目需求选择适合的实现方式,从简单到复杂都有相应的解决方案。






