semperton / routing
Semperton路由组件。
2.0.0
2022-06-21 13:57 UTC
Requires
- php: >= 7.4
- ext-ctype: *
- psr/http-message: ^1.0
Requires (Dev)
- phpbench/phpbench: ^1.0
- phpunit/phpunit: ^9.5
- vimeo/psalm: ^4.7
README
Semperton Routing
一个基于B-tree的轻量级PHP路由库。
支持自定义验证器和反向路由。
安装
只需使用Composer
composer require semperton/routing
路由需要PHP 7.4+
路由
所有路由都添加到RouteCollection
中。每个HTTP动词都有简写函数,以及一个通用的map()
方法。
use Semperton\Routing\Collection\RouteCollection; $routes = new RouteCollection(); $routes->map(['GET', 'POST'], '/blog/article/:id:d', 'article-handler'); $routes->get('/category/product', 'product-handler'); $routes->post('/user/login', 'login-handler'); // grouping $routes->group('/blog', function (RouteCollection $blog) { $blog->get('/article', 'article-handler'); $blog->get('/category', 'category-handler'); });
匹配
RouteMatcher
用于将请求方法和路径与所有定义的路由进行匹配。它使用RouteCollection
中的路由树并返回一个MatchResult
。
use Semperton\Routing\Matcher\RouteMatcher; $matcher = new RouteMatcher($routes); $result = $matcher->match('GET', '/blog/article/3'); $result->isMatch(); // true $result->getHandler(); // 'article-handler' $result->getParams(); // ['id' => '3']
占位符
您可以将路由的一部分替换为占位符。它们以冒号开头,后跟一个identifier:validator
组合。
:path -- no validator
:id:d -- digit validator
:name:w -- word validator
请注意,占位符必须占据两个斜杠之间的所有内容,例如/blog/:category/:id:d
。不允许使用多次替换,如/:document-:id.html
。您应考虑使用自定义验证器。
通配符
可以在路由的末尾使用通配符(捕获所有处理器)。
$routes->get('/*path', 'admin-handler'); $result = $matcher->match('GET', '/admin/users'); $result->getParams(); // ['path' => 'admin/users']
请注意,通配符始终最后评估。
验证器
有几个内置验证器可用。
:A -- ctype_alnum
:a -- ctype_alpha
:d -- ctype_digit
:x -- ctype_xdigit
:l -- ctype_lower
:u -- ctype_upper
:w -- ctype_alnum + _
您可以将自定义验证器添加到RouteMatcher
中进行占位符验证。
use Semperton\Routing\Collection\RouteCollection; use Semperton\Routing\Matcher\RouteMatcher; $routes = new RouteCollection(); $routes->get('/media/:filename:file', 'handler'); $matcher = new RouteMatcher($routes); $matcher->setValidator('file', function (string $value) { $parts = explode('.', $value, 2); if(isset($parts[1])){ return true; } return false; }); $matcher->validate('readme.txt', 'file'); // true $result = $matcher->match('GET', '/media/data.json'); $result->getParams(); // ['filename' => 'data.json']
反向路由
可以使用reverse()
方法使用RouteCollection
构建已知路由。
use Semperton\Routing\Collection\RouteCollection; $routes = new RouteCollection(); // add a named route $routes->get('/product/:id:d', 'product-route'); // build it $routes->reverse('product-route', ['id' => 42]); // '/product/42'