The Slim Framework support forum has moved to http://discourse.slimframework.com. This Tender forum is no longer maintained or monitored.

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

Martyn's Avatar

Martyn

18 Jan, 2016 10:13 AM

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?

  1. Support Staff 1 Posted by Andrew Smith on 18 Jan, 2016 01:21 PM

    Andrew Smith's Avatar

    You should be able to access it via $this->container, but this depends on how you added your middleware to the stack.

Reply to this discussion

Internal reply

Formatting help / Preview (switch to plain text) No formatting (switch to Markdown)

Attaching KB article:

»

Attached Files

You can attach files up to 10MB

If you don't have an account yet, we need to confirm you're human and not a machine trying to post spam.

Keyboard shortcuts

Generic

? Show this help
ESC Blurs the current field

Comment Form

r Focus the comment reply box
^ + ↩ Submit the comment

You can use Command ⌘ instead of Control ^ on Mac