httpsoft / http-router
简单快速的HTTP请求路由器,支持PSR-7和PSR-15
1.1.0
2023-05-05 22:02 UTC
Requires
- php: ^7.4|^8.0
- httpsoft/http-runner: ^1.1
Requires (Dev)
- httpsoft/http-message: ^1.1
- phpunit/phpunit: ^9.5
- squizlabs/php_codesniffer: ^3.7
- vimeo/psalm: ^4.9|^5.2
Provides
README
此包提供了对HTTP请求路由的便捷管理,支持PSR-7和PSR-15。
文档
安装
此包需要PHP版本7.4或更高版本。
composer require httpsoft/http-router
使用方法
use HttpSoft\Router\RouteCollector; /** * @var mixed $handler */ $router = new RouteCollector(); // Defining routes. $router->get('home', '/', $handler); $router->post('logout', '/logout', $handler); $router->add('login', '/login', $handler, ['GET', 'POST']); // Custom regular expressions for placeholder parameter tokens. $router->delete('post.delete', '/post/delete/{id}', $handler)->tokens(['id' => '\d+']); // Generate path '/post/delete/25' $router->routes()->path('post.delete', ['id' => 25]); // Generate url '//example.com/post/delete/25' $router->routes()->url('post.delete', ['id' => 25], 'example.com'); // Generate url 'https://example.com/post/delete/25' $router->routes()->url('post.delete', ['id' => 25], 'example.com', true);
将参数设置为默认值。
$router->get('post.view', '/post/{slug}{format}', $handler) ->tokens(['slug' => '[\w\-]+', 'format' => '\.[a-zA-z]{3,}']) ->defaults(['format' => '.html']) ; // Generate path '/post/post-slug.html'. $router->routes()->path('post.view', ['slug' => 'post-slug']);
位于[...]
内的路由令牌被视为可选。
$router->get('post.list', '/posts{[page]}', $handler) ->tokens(['page' => '\d+']) ; // '/posts/33' $router->routes()->path('post.list', ['page' => 33]); // '/posts' $router->routes()->path('post.list');
如有必要,您可以指定用于路由匹配的特定主机。
// Only for example.com $router->get('page', '/page', $handler) ->host('example.com') ; // Only for subdomain.example.com $router->get('page', '/page', $handler) ->host('subdomain.example.com') ; // Only for shop.example.com or blog.example.com $router->get('page', '/page', $handler) ->host('(shop|blog).example.com') ;
您可以在组内指定路由。
$router->group('/post', static function (RouteCollector $router): void { // '/post/post-slug' $router->get('post.view', '/{slug}', ViewHandler::class)->tokens(['slug' => '[\w-]+']); // '/post' or '/post/2' $router->get('post.list', '/list{[page]}', ListHandler::class)->tokens(['page' => '\d+']); }); // The result will be equivalent to: $router->get('post.view', '/post/{slug}', ViewHandler::class)->tokens(['slug' => '[\w-]+']); $router->get('post.list', '/post/list{[page]}', ListHandler::class)->tokens(['page' => '\d+']);
检查匹配的路由。
/** * @var mixed $handler * @var Psr\Http\Message\UriInterface $uri * @var Psr\Http\Message\ServerRequestInterface $request */ $router->get('page', '/page/{id}', $handler)->tokens(['id' => '\d+']); // Match $route = $router->routes()->match($request->withUri($uri->withPath('/page/11'))); $route->getMatchedParameters(); // ['id' => '11'] // Mismatch $router->routes()->match($request->withUri($uri->withPath('/page/slug'))); // null