gpt4 book ai didi

php - 使用类型提示和依赖注入(inject)

转载 作者:行者123 更新时间:2023-11-28 20:04:54 25 4
gpt4 key购买 nike

我正在使用 Type Hinting在将对象传递给其构造函数的类上。传递的对象 (Bar) 存在于它自己的命名空间中。这一切都很好,直到我用一个假的对象换掉传递的对象(用于单元测试目的)。我的测试 Bar 对象驻留在它自己的命名空间中,现在(非常正确地)抛出一个错误。

use Some\Place\Bar
class Foo {
// Passing a test Bar into here now throws error.
public function __construct(Bar $bar) {
$this->bar = $bar;
}

}

我是 PHP 的新手,所以不确定什么是可能的。有没有办法解决这个问题,还是我只需要从类中删除类型提示(这是我当前的解决方案)?

最佳答案

几个选项中的 2 个:

在实现接口(interface) IBar 的构造函数中传递一个对象:

 interface IBar{
function baz();
}

class Bar implements IBar{
function baz(){ return $this->getSomethingExpensiveFromDatabase();}
}

class FakeBar implements IBar{
function baz(){ return "baz";}
}

class Foo {
function __construct(IBar $bar) ...

或者不使用类型提示

function __construct($bar) 

重点是,方法的签名永远不应依赖于实现,而应始终依赖于接口(interface)。

编辑:所以您只需要导入接口(interface),然后导入假类,无论它来自哪里。然后 FakeBar 可以模拟 Bar。

关于php - 使用类型提示和依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14614991/

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