在控制器方法中访问 $this 时遇到问题

Trouble accessing $this in controller method

我正在通过 Slim 构建一个 API,并使用基于 class 的控制器方法。查看 router docs(在 "Allow Slim to instantiate the controller" 下),似乎 DI 应该将 ContainerInterface 插入到 class 构造函数中,然后我应该能够访问 $this->container 在 class 方法中访问容器。

我创建了一个基地 class:

class BaseController
{

    protected $container;

    public function __construct(\Interop\Container\ContainerInterface $container) {
        $this->container = $container;
    }

}

然后尝试这个:

class PMsController extends BaseController
{

    public function index(Request $request, Response $response, $args)
    {
        var_dump($this); exit;
    }

}

我的路线:

$app->group('/pms', function () {
    $this->get('', '\App\Controllers\PMsController::index');
})->add(authMiddlware());

但我收到错误:Using $this when not in object context。当它是 class 方法时,我不知道它是如何到达那里的。我不确定是否应该使用其他方法访问容器?

尝试将路线更改为

$app->group('/pms', function () {
    $this->get('', '\App\Controllers\PMsController:index');
})->add(authMiddlware());

请注意单 : 而不是双 ::。如果您不在其中执行任何附加功能,您也不需要 BaseController。 Slim 3 会默认为您注入 Container