Slim: Accessing the RouteParser

Created on 10 Sep 2019  路  4Comments  路  Source: slimphp/Slim

Hello,

I'm trying out Slim 4 for a new project and I found myself wanting to access the RouteParser for doing redirects from my routes callable.

I found #2758 which if I understand correctly enables the access to the RouteParser from the Request but when I try to access it I just get a null value.

Here is what I tested with the simplest example :

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

$app->get('/', function (Request $request, Response $response, $args) {
    die(var_dump($request->getAttribute('routingParser'))); /* <= gives me null */
    $response->getBody()->write("Hello world!");
    return $response;
});

$app->run();

Am I doing something wrong here ?

Thanks for your help

Most helpful comment

Try to use this helper instead:

$routeParser = \Slim\Routing\RouteContext::fromRequest($request)->getRouteParser();

All 4 comments

Try to use this helper instead:

$routeParser = \Slim\Routing\RouteContext::fromRequest($request)->getRouteParser();
$routeParser = $request->getAttribute('routeParser');

This gives me null as well

When I try the helper I get an exception :
Fatal error: Uncaught RuntimeException: Cannot create RouteContext before routing has been completed in /var/www/html/vendor/slim/slim/Slim/Routing/RouteContext.php on line 30

Make sure that the RoutingMiddleware is loaded.

$app = AppFactory::create();

$app->addBodyParsingMiddleware();
$app->addRoutingMiddleware(); // <---
$app->addErrorMiddleware(true, true, true);

// ...

$app->run();

Indeed it's working now.

Sorry I didn't catch that in the documentation. Thank you for your fast responses !

Was this page helpful?
0 / 5 - 0 ratings