在没有依赖项注入容器的情况下解决依赖项

时间:2020-02-01 13:35:09

标签: php testing dependency-injection

我有一个使用纯PHP的项目,并且有一个依赖于外部库的类。

我不认为将它传递给构造函数是一个好主意(主要是在测试中调用,但是软件包的用户必须将其传递给构造函数)。

我没有任何DI容器,也不认为应该拥有DI容器,因为该项目是一个小包装,只有几个类。

所以我想出了这种方法,想知道这种方法是否有任何后果或弊端,或者是否有其他解决方案?

    protected $client;

    /**
     * @param Client|null $client
     */
    public function __construct(Client $client = null)
    {
        $this->client = $client ?? new Client();
    }

2 个答案:

答案 0 :(得分:0)

也许对您有用?

dockerPlugin

答案 1 :(得分:0)

我没有发现任何重大问题。如果您的类没有注入默认的Client实现,那么它会退回到默认的interface IClient // maybe find a slightly more suitable name for it { // define Client's public interface methods here } 实现,但是由于您没有执行它,因此它保留了适当的灵活性/可测试性。

不过,我会进一步介绍并实现Dependency Inversion

class Client implements IClient 
{
  // ...
}

更改您的Client类以实现它:

public function __construct(IClient $client = null)
{
  $this->client = $client ?? new Client();
}

然后将构造函数更改为此:

Client

这样,您的类甚至根本不依赖任何实现。如果未明确为其指定默认值,则默认为{{1}}。