wandu/router

此包已被 废弃 并不再维护。未建议替代包。

带有 PSR-7 包装库的 FastRoute。

v4.0.0-beta2 2017-09-22 03:11 UTC

README

Latest Stable Version Latest Unstable Version Total Downloads License

带有 PSR-7 包装库的 FastRoute。

安装

composer require wandu/router

基本用法

$dispatcher = new \Wandu\Router\Dispatcher();
$routes = $dispatcher->createRouteCollection();

$routes->get('/', HomeController::class);
$routes->get('/users', UserController::class, 'index');
$routes->get('/users/:id', UserController::class, 'show');

$request = new ServerRequest('GET', '/'); // PSR7 ServerRequestInterface implementation
$response = $dispatcher->dispatch($routes, $request);

static::assertInstanceOf(ResponseInterface::class, $response);
static::assertEquals('index', $response->getBody()->__toString());

$request = new ServerRequest('GET', '/nothing'); // PSR7 ServerRequestInterface implementation
try {
    $dispatcher->dispatch($routes, $request);
} catch (RouteNotFoundException $e) {
    static::assertEquals('Route not found.', $e->getMessage());
}
class HomeController
{
    public static function index()
    {
        return new Response(200, new StringStream("index"));
    }
}

模式路由

$routes->get('/users/:id(\d+)?', UserController::class, 'show');
$routes->get('/users-:id', UserController::class, 'show');
class UserController
{
    public static function show(ServerRequestInterface $request)
    {
        return new Response(200, new StringStream("{$request->getAttribute('id')}"));
    }
}

您可以使用 path-to-regexp 中的所有模式。

参考