8000 [DX] Null Object pattern for 'LoggerInterface $logger' · Issue #15594 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[DX] Null Object pattern for 'LoggerInterface $logger' #15594

@AlexDpy

Description

@AlexDpy

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0