Add extra parameters to Middleware in Slim 3

Is it possible to add parameters to a middleware function?

$app->get('/user',  function($request, $response, $args) {
  ...
})->add(mwAuth(['users.list']));

In the mwAuth function I would like to process the parameter to return 403 or proceed to the route. Otherwise I have to make a new middleware function for every route, or [switch-case] every route path (not an option).

You could look into using a class for your middleware. This will allow you to pass in parameters using the constructor.

E.g.

class MwAuth
{
    private $action;

    public function __construct($action)
    {
        $this->action = $action;
    }

    public function __invoke($request, $response, $next)
    {
        // process using $action parameter
    }
}

and

$app->get('/user',  function($request, $response, $args) {
  ...
})->add(new MwAuth(['users.list']));

Returning an anonymous function might also work, e.g:

$app->get('/user',  function($request, $response, $args) {
  ...
})->add(return function($request, $response, $next) use($action) { return mwAuth($request, $response, $next, $action); });

and

function mwAuth($request, $response, $next, $action) {
    // process using $action parameter
}
1 Like

That should do the trick, Thx for quick response!