I've set up a new app based on the SlimPHP team's Slim Skeleton application. Inside of my route definitions, I want to be able to access the route parser as described in the Slim4 documentation. So, for example, I'd like to be able to edit the skeleton's app/routes.php file something like this:
$app->get('/', function (Request $request, Response $response) {
$routeParser = $app->getRouteCollector()->getRouteParser(); // this doesn't work
$response->getBody()->write('Hello world! ' . $routeParser->urlFor('something'));
return $response;
});
It makes sense that $app->getRouteCollector()->getRouteParser()
doesn't work, because $app
isn't defined here. But I would think that we'd instead call $this->getRouteCollector()->getRouteParser();
, but that gives the error: "Call to undefined method DI\\Container::getRouteCollector()"
.
It definitely seems that my confusion is about Dependency Injection, which is new for me and not coming naturally to me. I'd honestly love to define the $routeParser variable somewhere else (inside index.php?) so that I could access it in any route definition without having to call $app->getRouteCollector()->getRouteParser() every time. But at the moment I'd settle for anything that worked.
use
or pass anything by reference, so I don't think that points to the best way. – Rudolfrudolfouse
ing$app
was common (in your case$app->get('/', function (Request $request, Response $response) use ($app) { ... }
). It might not be a recommended way in Slim, can't say for sure. – Filiation