php8,显式路由实现路由代码找到应用,方法,控制器,请给出代码
在 PHP 8 中实现显式路由,可以使用一个简单的路由器类来解析 URL 并调用相应的控制器和方法。以下是一个基本的实现示例:
<?php
class Router
{
private $routes = [];
public function addRoute($method, $path, $controller, $action)
{
$this->routes[] = [
'method' => $method,
'path' => $path,
'controller' => $controller,
'action' => $action
];
}
public function dispatch($method, $path)
{
foreach ($this->routes as $route) {
if ($route['method'] === $method && $route['path'] === $path) {
$controllerName = $route['controller'];
$actionName = $route['action'];
if (class_exists($controllerName)) {
$controller = new $controllerName();
if (method_exists($controller, $actionName)) {
return $controller->$actionName();
} else {
throw new Exception("Action $actionName not found in controller $controllerName");
}
} else {
throw new Exception("Controller $controllerName not found");
}
}
}
throw new Exception("No route found for $method $path");
}
}
<?php
class HomeController
{
public function index()
{
return "Welcome to the Home Page!";
}
public function about()
{
return "This is the About Page.";
}
}
<?php
require 'Router.php';
require 'HomeController.php';
$router = new Router();
// 添加路由
$router->addRoute('GET', '/', 'HomeController', 'index');
$router->addRoute('GET', '/about', 'HomeController', 'about');
// 获取请求方法和路径
$method = $_SERVER['REQUEST_METHOD'];
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
try {
$response = $router->dispatch($method, $path);
echo $response;
} catch (Exception $e) {
http_response_code(404);
echo $e->getMessage();
}
将上述代码保存为 PHP 文件并在服务器上运行。例如,将其保存为 index.php
并在浏览器中访问 http://yourdomain.com/
和 http://yourdomain.com/about
。
这个示例展示了如何使用显式路由来解析 URL 并调用相应的控制器和方法。你可以根据需要扩展这个基本的路由器类,例如添加参数支持、中间件、命名路由等。