Slim 4 get route identifier

Hi.
I’m trying to get the route identifier but it returns null.

$app = \Slim\Factory\AppFactory::create();

$app->get('/', function (Request $request, Response $response, array $args) use ($app) {
    $response->getBody()->write('Hello World');
    $response = $response->withAddedHeader('Content-Type', 'text/html');
    return $response;
})->setName('home');

$app->addRoutingMiddleware();

$identifier = $app->getRouteResolver()->computeRoutingResults($request->getUri(), $request->getMethod())->getRouteIdentifier();

Do you know the reason ?
Thanks.

You may add the middleware first…

$app = \Slim\Factory\AppFactory::create();
$app->addRoutingMiddleware();

// Routes ...

… and start the Slim application to get the result:

$app->run();

I tried this:

$app = \Slim\Factory\AppFactory::create();
$app->addRoutingMiddleware();

$app->get('/', function (Request $request, Response $response, array $args) use ($app) {
    $response->getBody()->write('Hello World');
    $response = $response->withAddedHeader('Content-Type', 'text/html');
    return $response;
})->setName('home');

$app->run();

$request = ServerRequestCreatorFactory::create()->createServerRequestFromGlobals();
var_dump($app->getRouteResolver()->computeRoutingResults($request->getUri(), $request->getMethod())->getRouteIdentifier());

But it returns null.

That’s not how Slim works. Slim creates its own ServerRequest variable. It makes no sense to create a custom ServerRequest “outside” the Slim scope. Afaik, you can only get the right route context within a middleware and controller action.

This should do the trick:

$app = \Slim\Factory\AppFactory::create();
$app->addRoutingMiddleware();

$app->get('/', function (Request $request, Response $response) {
    $routeIdentifier = \Slim\Routing\RouteContext::fromRequest($request)->getRoutingResults()->getRouteIdentifier();
    var_dump($routeIdentifier);
});

$app->run();
1 Like

Ah ok. I thought that slim just used the ServerRequestCreatorFactory to create the request object.
Thanks.

Ps. I saw some of your packages. Nice work. :wink:

1 Like