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:
- a) breaks the injection by classname for the other classes
- b) is apparently not a best practice
So what is the correct way to get this logger injected in the middleware?
Without adding the
LoggerInterface
as a named entry to the container, could you just inject theLoggerInterface
class directly to your middleware via$container->get()
? I.E. in aroutes.php
App function: