pwm / sfw-router
一个简单的路由器,用于将传入请求映射到预定义的处理程序
1.1.0
2017-07-03 13:47 UTC
Requires
- php: >=7.1.0
- pwm/sfw-request: ^1.0
Requires (Dev)
- phpunit/phpunit: ^6.1
This package is auto-updated.
Last update: 2024-09-29 02:18:41 UTC
README
一个简单的路由器,用于将传入请求映射到预定义的处理程序。
它使用预定义URI的段作为内部节点构建一棵树,并使用相应的处理程序作为终端节点。通过遍历此树来解析路由。
支持通配符段,并捕获用于处理程序的用法。详见使用说明。
精确段匹配优于通配符匹配。例如,如果你定义了/foo/bar
和/foo/{x}
作为具有相应处理程序Bar
和X
的路由,则/foo/bar
将由Bar
处理,而/foo/baz
将由X
处理。
目录表
需求
PHP 7.1+
安装
composer require pwm/sfw-router
使用
// Router depends on Request use SFW\Request\Request; use SFW\Request\RequestMethod as Method; use SFW\Request\RequestUri as Uri; // Have some controllers class FooCtrl { public function getAll(Request $request): array { /* ... */ } public function post(Request $request): bool { /* ... */ } } class BarCtrl { public function getById(Request $request, $fooId, $barId): Bar { /* ... */ } } // Create router $router = new Router(); // Add routes and corresponding route handlers $router->add(new Route(new Method(Method::GET), new Uri('/foo')), new RouteHandler(FooCtrl::class, 'getAll')); $router->add(new Route(new Method(Method::POST), new Uri('/foo')), new RouteHandler(FooCtrl::class, 'post')); $router->add(new Route(new Method(Method::GET), new Uri('/foo/{id}/bar/{id}')), new RouteHandler(BarCtrl::class, 'getById')); // Resolve a handler for an incoming request $routeHandler = $router->resolve(new Route($request->getMethod(), $request->getUri())); // (Optional) Resolve the handler class from the container and call the handling method $response = $container ->resolve($routeHandler->getClassName()) ->{$routeHandler->getMethodName()}($request, ...$routeHandler->getRoute()->getCapturedSegments());
工作原理
待定
测试
$ vendor/bin/phpunit
$ composer phpcs
$ composer phpstan