hulotte / routing
简单路由系统
1.1.0
2021-03-30 06:46 UTC
Requires
- php: ^8.0
- guzzlehttp/psr7: ^1.7.0
- psr/http-server-handler: ^1.0.1
- psr/http-server-middleware: ^1.0.1
Requires (Dev)
- phpunit/phpunit: ^9.5.0
- squizlabs/php_codesniffer: ^3.5.8
README
描述
Hulotte Routing 是一个简单路由系统。该包遵循 PSR7 标准。
安装
安装 Hulotte Routing 最简单的方式是使用 Composer 并执行以下命令
$ composer require hulotte/routing
如何声明路由?
实例化 RouteDispatcher 类
$dispatcher = new \Hulotte\Routing\RouteDispatcher();
使用 addRoute 方法添加路由。必要的参数包括:路径、名称和可调用对象。
$dispatcher->addRoute('/accueil', 'accueil', function(){ return 'Hello World'; });
您可以使用最后一个参数指定方法(默认为 'GET')。
$dispatcher->addRoute('/accueil', 'accueil', function(){ return 'Hello World'; }, 'POST'); $dispatcher->addRoute('/accueil', 'accueil', function(){ return 'Hello World'; }, ['GET', 'POST']);
您可以使用流畅的方式添加更多路由
$dispatcher->addRoute('/accueil', 'accueil', function(){ return 'Hello World'; }) ->addRoute('/blog', 'blog', function(){ return 'Welcome on my blog'; });
带有参数
参数需要这样声明:{parameterName:parameterRegex},每个参数需要用 '/' 分隔。参数将通过导入请求在可调用对象中可用。
$dispatcher->addRoute('/article/{id:\d+}/{slug:[a-z-]*}', 'accueil', function(ServerRequestInterface $request){ $params = $request->getAttributes(); });
如何使用路由系统?
声明路由后,有两种方式可以使用 Hulotte Routing
手动方法
使用示例
// $request is an object that implements ServerRequestInterface // Response is an object that implements ResponseInterface $route = $dispatcher->match($request); if ($route === null) { return new Response(404, [], 'Not found !'); } $callable = $route->getCallable(); return new Response(200, [], call_user_func_array($callable, [$request]));
使用类作为回调
您可以使用类或类方法作为回调。
如果您想为每个路由使用一个类
class MyClass { public function __invoke(ServerRequestInterface $request) { return 'Hello World'; } } Return New Response(200, [], call_user_func_array(new MyClass(), [$request]));
或如果您想将类方法用作回调
class MyClass { public function myMethod(ServerRequestInterface $request) { return 'Hello World'; } } Return New Response(200, [], call_user_func_array([new MyClass(), 'myMethod'], [$request]));
中间件
有一个 RouterMiddleware 类可用。该中间件在 URL 结尾添加斜杠并返回 301 重定向,如果路由不存在则返回 404 错误并创建响应。
在使用中间件之前,必须实例化 RouteDispatcher 并定义路由。
new \Hulotte\Middlewares\RoutingMiddleware($dispatcher);
可以定义自定义的可调用对象用于 404 错误。
$routingMiddleware = new \Hulotte\Middlewares\RoutingMiddleware($dispatcher); $routingMiddleware->setNotFoundCallable(function(){ return 'Oups, not found !'; });
重要!
如果您使用类方法作为回调与中间件,路由名称必须与类名称相同。
同样,如果您为 notFoundCallable 定义类方法,类方法名称必须是 'notFoundCallable'。