分组

为了将路由组织成逻辑分组, Slim\App 还提供了 group() 方法。每个分组的路由模式都会添加到其中包含的路由或分组之前,并且分组模式中的任何占位符参数最终都可以在嵌套路由中使用:

use Slim\Routing\RouteCollectorProxy;
// ...

$app->group('/users/{id:[0-9]+}', function (RouteCollectorProxy $group) {
    $group->map(['GET', 'DELETE', 'PATCH', 'PUT'], '', function ($request, $response, array $args) {
        // 根据$args['id']查找、删除、修改或替换用户
        // ...

        return $response;
    })->setName('user');

    $group->get('/reset-password', function ($request, $response, array $args) {
        // 路由为 /users/{id:[0-9]+}/reset-password
        // 重置$args['id']所代表用户的密码
        // ...

        return $response;
    })->setName('user-password-reset');
});

分组模式可以为空,以便对不共享常规模式的路由进行逻辑分组。

use Slim\Routing\RouteCollectorProxy;
// ...

$app->group('', function (RouteCollectorProxy $group) {
    $group->get('/billing', function ($request, $response, array $args) {
        // 路由为 /billing
        return $response;
    });

    $group->get('/invoice/{id:[0-9]+}', function ($request, $response, array $args) {
        // 路由为 /invoice/{id:[0-9]+}
        return $response;
    });
})->add(new GroupMiddleware());

注意,在分组闭包内部,Slim 会将闭包绑定到容器实例上。

  • 在路由闭包内部, $this 被绑定到 Psr\Container\ContainerInterface 的实例上。