Php PSR日志-为什么LoggerAwareInterface和LoggerAwareTrait没有空默认值

Php PSR日志-为什么LoggerAwareInterface和LoggerAwareTrait没有空默认值,php,psr-3,Php,Psr 3,根据上的示例,在构造函数中注入记录器接口,默认值为NULL <?php use Psr\Log\LoggerInterface; class Foo { private $logger; public function __construct(LoggerInterface $logger = null) { $this->logger = $logger; } public function doSomething()

根据上的示例,在构造函数中注入记录器接口,默认值为NULL

<?php

use Psr\Log\LoggerInterface;

class Foo
{
    private $logger;

    public function __construct(LoggerInterface $logger = null)
    {
        $this->logger = $logger;
    }

    public function doSomething()
    {
        if ($this->logger) {
            $this->logger->info('Doing work');
        }

        // do something useful
    }
}
这很好,很有效,但如果我愿意这样做的话

<?php

use Psr\Log\LoggerInterface;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;

class Foo implements  LoggerAwareInterface
{
    use LoggerAwareTrait;

    public function __construct(LoggerInterface $logger = null)
    {
        $this->setLogger(  $logger );
    }

    public function doSomething()
    {
        if ($this->logger) {
            $this->logger->info('Doing work');
        }

        // do something useful
    }
}
所以基本上我可以将NULL引用传递到构造函数中,但是我不可能调用setter,因为NULL是不允许的。如果
Psr\Log\loggerawareiinterface
看起来像这样会更好

<?php

use Psr\Log\LoggerInterface;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;

class Foo implements  LoggerAwareInterface
{
    use LoggerAwareTrait;

    public function __construct(LoggerInterface $logger = null)
    {
        $this->logger = $logger;
    }

    public function doSomething()
    {
        if ($this->logger) {
            $this->logger->info('Doing work');
        }

        // do something useful
    }
}
<?php

namespace Psr\Log;

/**
 * Describes a logger-aware instance.
 */
interface LoggerAwareInterface
{
    /**
     * Sets a logger instance on the object.
     *
     * @param LoggerInterface $logger
     *
     * @return void
     */
    public function setLogger(LoggerInterface $logger = null);
}

我想你在这里混合了很多问题

示例用法显示了如何在应用程序中使用
psr/log
实现。它也做得很正确

因此,下一个问题是关于通过

如果构造函数接受null,则不应调用
setLogger
方法。
setLogger
方法只能接受
LoggerInterface
,它不需要意外地将logger对象本身设置为null

假设签名为
setLogger($logger=null)
。现在,如果像下面的示例那样调用
setLogger()
,您可以看到记录器将重置为null

$logger = new SomePSR-3Logger();
$foo = new Foo($logger);
$foo->setLogger();

如果你想实现PSR-3记录器,你应该考虑阅读:

希望有帮助


谢谢。

这不应该成为他们Github回购协议的问题,而不是问题吗?特别是,因为您以“根据您的示例…”开头,您的意思是:“虽然有许多用户组和论坛致力于提供通用PHP支持,但FIG不是其中之一…”?你的问题不是关于一般的PHP支持,而是一个只有开发人员才能回答的非常具体的问题(因为你问的是他们做出决定的背景)。事实上,但我认为这对更广泛的人群来说是相互关联的
public function __construct(LoggerInterface $logger = null)
{
    $this->setLogger($logger);
}
$logger = new SomePSR-3Logger();
$foo = new Foo($logger);
$foo->setLogger();