Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

slim

slim-3

I've been reading that in Slim v2, $app was bound to the middleware class. I'm finding this not to be the case in v3? Below is my middleware class, but I'm just getting undefined:

<?php
namespace CrSrc\Middleware;

class Auth
{
    /**
     * 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)
    {
        // before

var_dump($this->getContainer()); // method undefined
var_dump($this->auth); exit; // method undefined
        if (! $this->get('auth')->isAuthenticated()) {
            // Not authenticated and must be authenticated to access this resource
            return $response->withStatus(401);
        }

        // pass onto the next callable
        $response = $next($request, $response);

        // after


        return $response;
    }
}

What's the correct way to access the DI container within middleware? I'm guessing there ought to be a way?

like image 446
Martyn Avatar asked Jan 17 '16 14:01

Martyn


1 Answers

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

<?php
namespace 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')
like image 133
the-noob Avatar answered Oct 19 '22 23:10

the-noob