Slim4 + PHP-DI + router service

Hello,
I was used to have the “router” service in the container for both

  1. inject it in my controllers in case I need to force a redirect
  2. pass to the php renderer and use it in my templates to echo the <a href attribute.

With slim4 I am able to do this:
$container->set(‘router’, $app->getRouteCollector()->getRouteParser());

This however implies that I can set the router only after having created the $app object.

What if I want to use PHP-DI autowiring and container builder? In this case $app is not defined because I need to build the container and pass it to the factory and create the $app after.

Thanks in advance.

Within your controller / action you should fetch get router from the $request object:

use Slim\Routing\RouteContext;

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

$url = $routeParser->urlFor('root');

What if I want to use PHP-DI autowiring and container builder? In this case $app is not defined because I need to build the container and pass it to the factory and create the $app after.

You could add a (PHP-DI) container definition for Slim App::class and the RouteContext::class. Then you are able to inject the Router where you need it.

Thankyou for your response.
I was aware of this method to obtain the routeParser. I was wondering if it was a way to put it in the container. At this point, I will definitely do like you suggest, maybe putting this code in a middleware so I can access the routeParser everywhere and find another way to make it available in every template.

cheers