Reputation: 1093
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
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
Reputation: 12778
Enable the determineRouteBeforeAppMiddleware
setting:
$config = ['settings' => [
'determineRouteBeforeAppMiddleware' => true,
'displayErrorDetails' => true,
]];
$app = new \Slim\App($config);
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