phpslimphp-diphp-figpsr-11

Dependency injection in PHP (slim, php-di)


I have a Slim Php (slim4) application to which I added Monolog for logging purposes. I'm adding the logger to the application like this:

$containerBuilder->addDefinitions([
  LoggerInterface::class => function (ContainerInterface $c) {
     $logger = new Logger('appname');
     ...
     return $logger

This works fine for injecting the logger in most of my classes, by just doing:

public function __construct(ContainerInterface $container = null, LoggerInterface $logger)
{
    // I can use $logger here

Now I'd also like to use the logger in the middleware like authentication. I don't see how I can properly do this. I can get this working by adding the logger as a named entry in the container like this:

$containerBuilder->addDefinitions([
  "LoggerInterface" => function (ContainerInterface $c) {

and then passing it to the middleware as a constructor parameter by getting it back from the container:

$middlewares[] = new MyAuthentication(..., $container->get('LoggerInterface'));

But this:

So what is the correct way to get this logger injected in the middleware?


Solution

  • Without adding the LoggerInterface as a named entry to the container, could you just inject the LoggerInterface class directly to your middleware via $container->get()? I.E. in a routes.php App function:

    $container = $app->getContainer();
    $app->add(new MiddleWare\MyAuthentication(..., $container->get(LoggerInterface::class)));