php使用fastroute路由
php 使用 fastroute 示例
- 首先,我们需要先使用 Composer 将 Fastroute 库引入到我们的项目中。在命令行中切换到项目根目录下,执行以下命令:
$ composer require nikic/fast-route
- 创建一个 index.php 文件,并在其中引入 vendor/autoload.php 文件来自动加载 Fastroute 库。
<?php
require_once __DIR__ . '/vendor/autoload.php';
- 创建一个 routes.php 文件来设置我们的路由。在此文件中,我们可以使用
$dispatcher->dispatch()
方法来匹配请求的路由,并执行相应的处理程序。
<?php
return [
['GET', '/', 'HomeController@index'],
['GET', '/about', 'AboutController@index'],
['GET', '/contact', 'ContactController@index'],
];
- 在 index.php 文件中,我们需要创建一个$dispatcher对象并调用$dispatcher->dispatch()方法来检索请求的路由。
<?php
require_once __DIR__ . '/vendor/autoload.php';
$dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $router) {
$routes = include(__DIR__ . '/routes.php');
foreach($routes as $route) {
$router->addRoute($route[0], $route[1], $route[2]);
}
});
$httpMethod = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];
$routeInfo = $dispatcher->dispatch($httpMethod, $uri);
switch ($routeInfo[0]) {
case FastRoute\Dispatcher::NOT_FOUND:
// 404 Not Found
break;
case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
$allowedMethods = $routeInfo[1];
// 405 Method Not Allowed
break;
case FastRoute\Dispatcher::FOUND:
$handler = $routeInfo[1];
$vars = $routeInfo[2];
// 解析控制器和方法
list($class, $method) = explode('@', $handler, 2);
// 创建控制器的实例
$controller = new $class;
// 调用方法,并传递变量
call_user_func_array([$controller, $method], $vars);
break;
}
我们在这个示例中使用了简单调度器(simpleDispatcher)来配置路由,但是您还可以选择其他的调度器来满足您的需求。此外,我们还需要根据我们的实际情况来编写控制器和方法。