I am missing some kind of best practice for implementation of PHP dependency injection and the PSR LoggerInterface.
Currently (without dependency injection) I have created my own LoggerFactory with this implementation in all classes with logging.
$logger = LoggerFactory::getLogger(__CLASS__);
By using this approach I can easily configure instantiation of Logger-objects with different logging threshold in the different classes.
But how should I implement instantiation of classes implementing LoggerInterface in the dependency injection to keep this support for different logging threshold?
Unfortunately PSR does not have a LoggerFactoryInterface I could use in the dependency injection.
-
Welcome to Stack Overflow. Please take the tour to learn how Stack Overflow works and read How to Ask on how to improve the quality of your question. It is unclear what you are asking or what the problem is. Please edit your question to include a more detailed description of the problem you have. Explain in detail where you are stuck.Progman– Progman2025年12月13日 00:13:18 +00:00Commented Dec 13, 2025 at 0:13
1 Answer 1
Dependency injection framework differs in how object instances are instantiated. It mostly depends on the library you used as container. Symfony needs you to create some YML configurations. PHP-DI has its own definition pattern.
It is totally OK to create your own interface if you were to do all of the implementations anyway.
For example,
use Psr\Log\LoggerInterface;
interface MyLoggerFactoryInterface {
public function getLogger(): LoggerInterface;
}
class MyTextLogger implements MyLoggerFactoryInterface {
public function getLogger(): LoggerInterface {
// some logic to create a logger
// ....
return $myLogger;
}
}
class MyHelloController {
public function __construct(private MyLoggerFactoryInterface $loggerFactory) {
}
...
public function handleIndex() {
$logger = $this->loggerFactory->getLogger();
// ...
$this->logger->info("something");
// ...
}
}
// Assume you're using PHP DI (without autowiring)
$container = new DI\Container([
MyTextLogger::class => create(),
MyHelloController::class => create()->constructor(
get(MyTextLogger::class),
),
]);
// ...
$container->get(MyHelloController::class)->handleIndex();