以下是一个简单的PHP路由类示例:
class Router {
private $routes;
public function __construct() {
$this->routes = array();
}
public function addRoute($pattern, $callback) {
$this->routes[$pattern] = $callback;
}
public function handleRequest($url) {
foreach ($this->routes as $pattern => $callback) {
if (preg_match($pattern, $url, $matches)) {
array_shift($matches); // 移除第一个元素(完整匹配)
call_user_func_array($callback, $matches);
return;
}
}
// 如果没有匹配的路由,则显示404页面
header("HTTP/1.0 404 Not Found");
echo "404 Not Found";
}
}
// 创建路由对象
$router = new Router();
// 添加路由规则
$router->addRoute('/^\/hello\/(\w+)/', function($name) {
echo "Hello, $name!";
});
$router->addRoute('/^\/users\/(\d+)/', function($id) {
echo "User ID: $id";
});
// 处理请求
$router->handleRequest($_SERVER['REQUEST_URI']);
使用该路由类,你可以在PHP服务器中进行路由处理。在上面的示例中,我们创建了一个Router
类,它具有addRoute
方法用于添加路由规则,并且具有handleRequest
方法用于处理请求。
通过调用addRoute
方法,你可以添加不同的路由规则,每个规则都有一个正则表达式模式和一个回调函数。当请求的URL与某个路由规则匹配时,回调函数将被调用,并且可以传递URL中的参数。
在示例中,我们添加了两个路由规则,一个用于处理/hello/{name}
形式的URL,另一个用于处理/users/{id}
形式的URL。当请求的URL匹配到某个路由规则时,回调函数将被调用,并且可以使用URL中的参数。
最后,我们调用handleRequest
方法来处理当前请求。如果没有匹配的路由规则,则返回404页面。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站