Manrix
September 23, 2019, 3:08pm
1
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.
odan
September 24, 2019, 10:55am
2
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();
Manrix
September 24, 2019, 12:18pm
3
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
.
odan
September 24, 2019, 1:45pm
4
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
Manrix
September 24, 2019, 2:15pm
5
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.
1 Like