php 实现路由规则
路由规则实现方法
在PHP中实现路由规则通常涉及解析URL请求并将其映射到对应的控制器和操作方法。以下是几种常见的实现方式:
基础路由实现
通过解析$_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';
break;
}
正则表达式路由
更灵活的路由方案可以使用正则表达式匹配:
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
if (preg_match('#^/user/(\d+)$#', $uri, $matches)) {
$userId = $matches[1];
require 'user_profile.php';
} elseif ($uri === '/contact') {
require 'contact.php';
} else {
http_response_code(404);
require '404.php';
}
路由类实现
封装成更结构化的路由类:
class Router {
private $routes = [];
public function addRoute($pattern, $handler) {
$this->routes[$pattern] = $handler;
}
public function dispatch() {
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
foreach ($this->routes as $pattern => $handler) {
if (preg_match("#^$pattern$#", $uri, $matches)) {
array_shift($matches);
call_user_func_array($handler, $matches);
return;
}
}
http_response_code(404);
echo '404 Not Found';
}
}
$router = new Router();
$router->addRoute('/user/(\d+)', function($id) {
echo "User ID: $id";
});
$router->addRoute('/about', function() {
echo 'About Page';
});
$router->dispatch();
现代框架路由方案
多数现代PHP框架使用更高级的路由系统:
-
Laravel风格路由:
Route::get('/user/{id}', function($id) { return view('user.profile', ['userId' => $id]); }); -
Slim框架路由:
$app->get('/user/{id}', function ($request, $response, $args) { return $response->write("User ID: ".$args['id']); });
路由缓存优化
对于生产环境,可以考虑路由缓存机制:
if (file_exists('routes.cache')) {
$routes = unserialize(file_get_contents('routes.cache'));
} else {
$routes = buildRoutes(); // 构建路由配置
file_put_contents('routes.cache', serialize($routes));
}
RESTful路由实现
支持HTTP动词的路由方案:
$method = $_SERVER['REQUEST_METHOD'];
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
if ($method === 'GET' && $uri === '/users') {
// 获取用户列表
} elseif ($method === 'POST' && $uri === '/users') {
// 创建用户
} elseif ($method === 'GET' && preg_match('#^/users/(\d+)$#', $uri, $matches)) {
// 获取单个用户
$userId = $matches[1];
}
路由参数验证
添加参数类型验证:

$router->addRoute('/post/{id:\d+}', function($id) {
// 只匹配数字ID
});
$router->addRoute('/category/{slug:[a-z-]+}', function($slug) {
// 只匹配小写字母和连字符
});
以上方案可以根据项目需求选择或组合使用,从简单到复杂满足不同规模应用的路由需求。






