Q:

Creating a global user variable

I’m new to slim and trying to figure out the best way to create a global user variable. My first thought is to add it to the Container, but I can’t figure out how to inject $app into a route mapped to a class method. I saw somewhere that I can add Container $container to the constructor and the DI should do it automatically? Doesn’t seem to be working.
__construct(Container $container)

Plus, I need to access the variable in a middleware class I wrote to parse my Bearer header, and I can’t find any details on how to do that. I know I can pass $app into each ->add, but that’s a lot of repeated code, and I’m hoping I can avoid that. I'm already injecting an extra variable to parse for roles:
->add(new \App\Middleware\AuthMiddleware('admin'));

public function __construct($role = null)

I can always create a PHP global, but I'd like to figure out what the right Slim way of doing this is.

A:

You can do this with a CurrentUser-class which stores the roles:
class CurrentUser {
    private $roles;
    function getRoles() {return $this->roles; }
    function setRoles($newRoles) {$this->roles = $newRoles; }
}

Which then you can add to the container:
$container[CurrentUser::class] = function($c) {
    $user = new CurrentUser();
    $user->setRoles(['myrole']);
    return $user;
};

And use the CurrentUser-object in a helper method which dynamically creates us the wanted middleware. This method could also be on the CurrentUser-class
function hasPermission($role) {
    return function($req, $resp, $next) use ($role) {
        if(in_array($role, $this[CurrentUser::class]->getRoles())) {
            return $next($res, $resp); // proceed to route
        } else {
            // handle unauthorized
            return $resp->withStatus(401)->write('unauthorized');
        }
    };
}

Now use the helper method to create the middleware which authorize the user.
$app->get('/books', function ($request, $response, $args) {
    return $response->write('Some books yay');
})->add(hasPermission('myrole'));

