我正试图了解 DI。对于遵循 DI 模式的课程,我是否正确地做到了这一点?
class Boo
{
public $title = 'Mr';
public $name = 'John';
protected $deps;
public function __construct($deps)
{
$this->deps = $deps;
}
public function methodBoo()
{
return 'Boo method '.$this->deps;
}
}
class Foo
{
private $objects;
public function __construct()
{
}
// Set the inaccessible property magically.
public function __set($name, $value)
{
$this->$name = $value;
}
// Set the inaccessible $class magically.
public function __get($class)
{
if(isset($this->objects[$class]))
{
return $this->objects[$class];
}
return $this->objects[$class] = new $class($this->deps);
}
public function methodFoo()
{
return $this->Boo->methodBoo();
}
}
$Foo = new Foo();
$Foo->deps = 'says hello';
var_dump($Foo->methodFoo());
结果,
string 'Boo method says hello' (length=21)
在某些情况下,我不想使用构造注入,因为并非 Foo 中的所有方法都依赖于相同的注入。例如,methodFoo()
in仅Foo
依赖于Boo
,而其他方法依赖于其他类/注入。
另外,我也不想使用setter 注入,因为我可能必须在其中写很多Foo
,比如
setBoo() {}
setToo() {}
setLoo() {}
... and so on...
所以我想使用魔术方法__get
,__set
可以避免我最终写出一长串的清单。有了这个,我只在Foo
.
这是正确的做法吗?我以前没有用单元测试做过任何测试。这个解决方案可以测试吗?
或者你有什么更好的解决方案?