Rohit
Rohit

Reputation: 3156

Trouble accessing $this in controller method

I'm building an API via Slim, and using class based controller methods. Looking at the router docs (under "Allow Slim to instantiate the controller"), it seems like the DI should insert the ContainerInterface into the class constructor, and then I should be able to access $this->container in the class method to access the container.

I created a base class:

class BaseController
{

    protected $container;

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

}

And then tried this:

class PMsController extends BaseController
{

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

}

And my route:

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

But I get the error: Using $this when not in object context. I have no idea how that gets there, when it's a class method. I'm not positive if I should be using another method of accessing the container?

Upvotes: 1

Views: 85

Answers (1)

Andrew Smith
Andrew Smith

Reputation: 1851

Try changing your route to

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

Please note the single : rather than using double ::. You also don't need a BaseController if you aren't performing any additional feature in it. Slim 3 will inject the Container by default for you.

Upvotes: 1

Related Questions