istok / router
基本路由组件
0.0.3
2022-05-06 17:59 UTC
Requires
- php: ^8.1
- phpunit/phpunit: ^9.5
- vimeo/psalm: ^4.22
This package is auto-updated.
Last update: 2024-09-06 22:51:44 UTC
README
composer require istok/router
基本路由
- 将给定的
Request
(本质上array<string,string>
) 匹配到mixed $handler
- 包含适合 http 请求的实现
- 支持变量,例如
/post/{id}/
- 构建以与
istok/container
一起使用 - (希望)可以轻松扩展以路由除了
http
之外的内容(控制台,队列)
使用方法(目前没有提供糖代码)
在 example.com
中的工作示例,别忘了先安装依赖项。
use Istok\Router\Router; use Istok\Router\Route; use Istok\Router\Http\HttpTemplate; use Istok\Router\Http\HttpRequest; // define single router entry $route = new Route( // provide template interface new HttpTemplate('/post/{id}/show', 'GET', '{user}.example.com'), // provide handler fn($id, $user) => print "User: $user, id: $id" ); // setup router, add our single route $router = new Router($route); // special http-oriented implementation of Request interface $request = new HttpRequest('/post/abc/show', 'GET', 'user1.example.com'); // match route to request $result = $router->find($request); // execute result, // $result->arguments contains ['user' => 'user1', 'id' => 'abc'] ($result->route->handler)(...$result->arguments); // User: user1, id: abc
如何捕获模板的其余部分
最后的 path
$template = new HttpTemplate('/post/{url*}'),
将匹配 /post/abc/def
,参数为 ['url' => 'abc/def']
类似在 host
$template = new HttpTemplate('/', host: '{subdomain*}.example.com'),
将匹配 abc.def.example.com
,参数为 ['subdomain' => 'abc.def']