-
-
Notifications
You must be signed in to change notification settings - Fork 9.7k
Closed
Description
I noticed that most of the time in Symfony, when a LoggerInterface is injected into a service and when it can be null, we do not use the null-object pattern.
Psr\Log has a NullLogger that can be used in this case. It says :
/**
* This Logger can be used to avoid conditional log calls
*
* Logging should always be optional, and if no logger is provided to your
* library creating a NullLogger instance to have something to throw logs at
* is a good way to avoid littering your code with `if ($this->logger) { }`
* blocks.
*/
https://github.com/php-fig/log/blob/master/Psr/Log/NullLogger.php
If found 60 occurences of "if (null !== $this->logger)" in Symfony. Many of these could be avoided and the code could be clearer.
Before:
protected $logger;
public function __construct(LoggerInterface $logger = null)
{
$this->logger = $logger;
}
public function foo()
{
if (null !== $this->logger) {
$this->logger->info('foo');
}
}
public function bar()
{
if (null !== $this->logger) {
$this->logger->info('bar');
}
}
After:
protected $logger;
public function __construct(LoggerInterface $logger = null)
{
$this->logger = null === $logger ? new NullLogger() : $logger;
}
public function foo()
{
$this->logger->info('foo');
}
public function bar()
{
$this->logger->info('bar');
}
If you think it's a good idea, i can provide a PR.
Metadata
Metadata
Assignees
Labels
No labels