legomolina
legomolina

Reputation: 1093

Route pattern in middleware Slim v3

How can I get route pattern inside middleware:

routes.php:

$app->get('/myroute/{id}', function($req, $res, $args) {
//DO STUFF HERE
})->add(new MyMiddle());

middle.php:

class MyMiddle {
    public function __invoke($req, $res, $next) {
         //DO STUFF
    }
}

In routes.php I can get {id} with $args['id'], but how can I get it inside MyMiddle.php?

Thank you,
Cristian Molina

Upvotes: 2

Views: 1082

Answers (2)

Alex Barker
Alex Barker

Reputation: 4400

I decided to included a Slim v2 example as that is what I was looking for when I came across this post. You can use $this->app->router()->getCurrentRoute()->getPattern() from the slim.before.dispatch callback hook to accomplish the same thing.

Upvotes: 1

Rob Allen
Rob Allen

Reputation: 12778

  1. Enable the determineRouteBeforeAppMiddleware setting:

    $config = ['settings' => [
        'determineRouteBeforeAppMiddleware' => true,
        'displayErrorDetails' => true,
    ]];
    $app = new \Slim\App($config);
    
  2. You can now access the Route object from the Request, using getAttribute() and, from the route, get at the arguments:

    $app->add(function ($request, $response, $next) {
        $id = $request->getAttribute('route')->getArgument('id');
        return $next($request, $response);
    });
    

Upvotes: 4

Related Questions