gpt4 book ai didi

php - PSR 日志 - 为什么 LoggerAwareInterface 和 LoggerAwareTrait 没有 NULL 默认值

转载 作者:行者123 更新时间:2023-12-02 04:34:19 25 4
gpt4 key购买 nike

根据您的样本Github您可以在构造函数中注入(inject)记录器接口(interface),默认值为 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
}
}

表达某个东西有一个 Logger,您可以实现 Psr\Log\LoggerAwareInterfacePsr\Log\LoggerAwareTrait

重建示例代码,它看起来像这样

<?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

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
}
}

最终会出现必须是 Psr\Log\LoggerInterface 的实例,给定 null 错误,因为接口(interface)中的方法声明没有 NULL 默认值。当然,可以通过使用 if 进行保护或传递 NullLogger 来防止此错误,但这很奇怪。

能够在构造函数中传递可选的 Logger 实例将使我认为稍后可以通过将 Logger 设置为 NULL 值来更改该实例。当然,这是示例代码,但让我们看看问题

  public function __construct(LoggerInterface $logger = null);

public function setLogger(LoggerInterface $logger);

所以基本上我可以将 NULL 引用传递到构造函数中,但我无法调用 setter,因为不允许 NULL。如果 Psr\Log\LoggerAwareInterface 看起来像这样,那就更好了

<?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);
}

那么请告诉我这个决定的背景?

最佳答案

我认为您在这里混淆了很多问题。

示例用法https://github.com/php-fig/log#usage展示如何在应用程序中使用 psr/log 实现。它也做得正确。

所以下一个问题是关于 LoggerAwareInterface 的用法和通过 LoggerAwareTraitsetLogger 方法

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

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

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

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

如果您想实现 PSR-3 记录器,您应该考虑阅读:https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md

希望有帮助。

谢谢。

关于php - PSR 日志 - 为什么 LoggerAwareInterface 和 LoggerAwareTrait 没有 NULL 默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40401259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com