piernik
piernik

Reputation: 3657

Getting route path arguments in middleware

In Slim 3 I have group with the same actions which depends on $args:

$this->group('{id}/', function () {
    $this->get('first/', function (Request $req, Response $res, $args) {
        $myData = operations($args['id']);
        ...
    });

    $this->post('second/', function (Request $req, Response $res, $args) {
        $myData = operations($args['id']);
        ...
    });
});

I could transfer those common operations to higher level. As I read it could be middleware but in middleware I cannot (or don't know how) access to $args.

->add(function (ServerRequestInterface $request, ResponseInterface $response, callable $next) {
    //how to get arguments?
    $request = $request->withAttribute('myData', operations($id); 
    $response = $next($request, $response);

    return $response;
});

Upvotes: 1

Views: 1852

Answers (2)

yanot
yanot

Reputation: 353

Another way:

$route = $req->getAttribute('route');
if (! is_null($route)) {
    print_r($route->getArguments()); // ['id' => 123]
    print_r($route->getArgument('id')); // 123
}

Upvotes: 2

jmattheis
jmattheis

Reputation: 11115

You can access the route params with the third item of the route info attribute:

$routeParams = $request->getAttribute('routeInfo')[2];

Upvotes: 5

Related Questions