How to access the $container within middleware class in Slim v3? How to access the $container within middleware class in Slim v3? php php

How to access the $container within middleware class in Slim v3?


A bit late to the party but might help others... You have to inject your container when instantiating the middleware

$container = $app->getContainer();$app->add(new Auth($container));

And your middleware needs a constructor

<?phpnamespace CrSrc\Middleware;class Auth{    private $container;    public function __construct($container) {        $this->container = $container    }    /**     * Example middleware invokable class     *     * @param  \Psr\Http\Message\ServerRequestInterface $request  PSR7 request     * @param  \Psr\Http\Message\ResponseInterface      $response PSR7 response     * @param  callable                                 $next     Next middleware     *     * @return \Psr\Http\Message\ResponseInterface     */    public function __invoke($request, $response, $next)    {        // $this->container has the DI    }}

LE:Expanding a bit the initial answer, the container gets injected in the constructor if you supply the middleware as a class string

$app->add('Auth');

or

$app->add('Auth:similarToInvokeMethod')


As far as I understand the code, Slim (v3) works the following way:

  • if you pass a closure as middleware, then it calls bindTo with container as param.
  • if you pass a class/string that resolves to a class, then Slim creates the instance and passes the container as param to the constructor

    <?php$app->add(Auth);
  • otherwise (e.g. if you add a middleware instance created earlier) then it looks like you have to take care of passing all necessary references.