Slim PHP 访问路由组中的对象

Slim PHP access object in route group

你好我想创建一个可以在所有嵌套路由中使用的对象

use Slim\App;
use Slim\Http\Request;
use Slim\Http\Response;

return function (App $app) {

    $app->group('/api', function (App $app) {

        $this->user = \User::findOrFail(1);

        $app->get('/profile', function ($request, $response, $args) {
            var_dump($this->user);
        });

    });
};

我得到的错误是

Type: Slim\Exception\ContainerValueNotFoundException
Message: Identifier "user" is not defined.

为此你应该使用容器

$app = new \Slim\App();
$container = $app->getContainer();
$container['user'] = function () {
    //code
};