user1032531
user1032531

Reputation: 26331

Accessing parameters in Slim v3 middleware

According to http://www.slimframework.com/docs/concepts/middleware.html, route middleware is added as follows.

<?php
$app = new \Slim\App();

$mw = function ($request, $response, $next) {
    // How is $arg accessed?
    $response->getBody()->write('BEFORE');
    $response = $next($request, $response);
    $response->getBody()->write('AFTER');

    return $response;
};

$app->get('/ticket/{id}', function ($request, $response, $args) {
    $response->getBody()->write(' Hello ');
    // $arg will be ['id'=>123]
    return $response;
})->add($mw);

$app->run();

$arg will be the parameters array. How can this be accessed in the middleware?

http://help.slimframework.com/discussions/questions/31-how-pass-route-pram-to-middleware shows an approach to do so, however, appears to be an earlier release of Slim, and errors Fatal error: Call to undefined method Slim\\Route::getParams().

Upvotes: 0

Views: 1250

Answers (1)

Gareth Parker
Gareth Parker

Reputation: 5062

Route Params can be accessed through the routeInfo Attribute on Request, as such

$app->get('/hello/{name}', \HelloWorld::class . ':execute')
    ->add(function ($request, $response, $next) {
        var_dump($request->getAttribute('routeInfo')[2]['name']);exit();
        return $next($request, $response);
    });

This is noted in this Github issue

Upvotes: 2

Related Questions