Access to the container in a middleware-class

I would like to have access to the containers in my own invokable middleware-class. Right now I added a construct method that is getting passed the app-object from the route. Is this the best way?

routes.php:
$app->get('/sessies/new', '\App\Controllers\SessiesController:newSession')->setName('newsession')->add(new \App\Middleware\CheckLogin($app));

CheckLogin:
class CheckLogin {
private $app;
public function __construct(App $app) {
$this->app = $app;
}
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) {
$flash = $this->app->getContainer()->get(‘flash’);

}
}

It’s better to provide all dependencies to constructor instead of container. :slight_smile:

1 Like

I agree. Rather than repeat why, here’s something I prepared earlier: http://www.anthonychambers.co.uk/blog/don’t-inject-dependency-injection-containers/14