mizmoz/router

Mizmoz 路由器

1.0.0 2024-09-27 03:05 UTC

This package is auto-updated.

Last update: 2024-09-27 03:09:39 UTC


README

一个简单的 HTTP 路由器

目标

  • 轻量级
  • 使用 PSR-7 HTTP 消息接口
  • 使用 PSR-15 HTTP 服务器中间件(当它标准化时,也许,现在很混乱)
  • 使用 PSR-11:容器接口进行解析

基本用法

// create a simple route
$route = Route::get('/', function (RequestInterface $request, ResponseInterface $response, ResultInterface $result) {
  return $response;
});

// init with a PSR-11 compatible container for class resolution
$dispatcher = new Router($route, $container);

// dispatch the route by passing a PSR-7 compatible Request
$response = $dispatcher->dispatch(new ServerRequest('GET', '/'));

exit($response->getBody()->getContents());

更多示例

// class callback which will call the default process($request, $response, $next);
Route::get('/admin', AdminController::class);

// class callback with specific method
Route::get('/admin', [AdminController::class, 'home']);

// Route to app\actions\User\GetProfile.php
Route::get('/profile/{:userId}', 'User\GetProfile');

// A more complete route
Route::get('/', HomePage::class, function (RouteInterface $r) {
    // add some child routes
    $r->addRoute('GET', '/profile', ...);
});

// wildcard matching
Route::get('/app/*', AppController::class);

带有变量的路由

// create the route with simple variable matching using :variable format
$route = new Route('GET', '/users/:userId', UserGet::class);

// get the variable
$userId = $route->match('GET', '/users/123')->getVariable('userId');

从请求中获取路由结果对象,无论是路由端点还是中间件

public function myMethod(ServerRequestInterface $request, ...)
{
    var_dump($request->getAttribute(Dispatcher::ATTRIBUTE_RESULT_KEY));
}

中间件

// add global middleware
$router->addMiddleware(new EnsureSsl());

// add middlware to a route, middleware is added before the route definition by default
$router->get('admin', AdminController::class)
    ->addMiddleware(new EnsureSsl());

// add to all routes
$router->get('/', function (RouteInterface $r) {
    $r->get('/users', ...);
})->addMiddleware(new AclUser('admin'));

路线图

  • 为类添加 REST API 辅助函数
  • 允许回退/通配符/错误路由