0

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().

user1032531
  • 24,767
  • 68
  • 217
  • 387

1 Answers1

2

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

Gareth Parker
  • 5,012
  • 2
  • 18
  • 42
  • 1
    You will need to use a Slim applications setting in order for this to work. determineRouteBeforeAppMiddleware => true ... http://www.slimframework.com/docs/objects/application.html#slim-default-settings – geggleto Aug 22 '16 at 15:29
  • Possibly, but that code as written was copy pasted from a runnable example myself. Having that setting to true could stop any unforseen problems though – Gareth Parker Aug 22 '16 at 15:35
  • Thanks Gareth. I tested this code, and it works as is. Given the lack of good documentation, I am a little concerned that it might not be supported in future revisions. – user1032531 Aug 22 '16 at 15:58