Php,lazy DI:添加一个lazy创建对象的闭包可以吗?
我们都知道这个经典的DI示例:Php,lazy DI:添加一个lazy创建对象的闭包可以吗?,php,dependency-injection,Php,Dependency Injection,我们都知道这个经典的DI示例: class Test2 { } class Test { private $obj; public __constructor (Test2 $obj) { $this->obj = $obj; } public function use() { $this->obj-> } } $test2 = new Test2(); $test = new Te
class Test2
{
}
class Test
{
private $obj;
public __constructor (Test2 $obj)
{
$this->obj = $obj;
}
public function use()
{
$this->obj->
}
}
$test2 = new Test2();
$test = new Test($test2);
到目前为止还不错,但是如果要插入的对象不存在,你知道,也许它甚至不必存在呢?如果永远不会调用use()
,在这种情况下,实例化Test2
是无用的。这里有一个可能的解决方案:但仍然存在一个(虚假且无用的)代理实例
如果我这样做怎么办:
class Test2
{
}
class Test
{
private $objClosure, $obj;
public __constructor (Closure $objClosure)
{
$this->objClosure = $objClosure;
}
public function use()
{
if ($this->obj == null)
{
$this->obj = $this->objClosure->__invoke();
}
$this->obj->
}
}
$test = new Test(function() { return new Test2(); });
这可能更复杂(需要更多的代码),但我觉得还可以。还有其他人吗?你为什么问?我的意思是,你是需要解决一个特定的用例,还是只是好奇?“还好吗…?”的问题:我的答案是,如果它能工作——就像在解决你的问题中一样——并且在6个月后可以为下一个人或你维护,那么它就没事了:)因为我想知道是否有人想到过这一点,如果有人能看到这样做的任何陷阱,你为什么问?我的意思是,你是需要解决一个特定的用例,还是只是好奇?“还好吗…?”的问题:我的答案是,如果它能工作——就像解决你的问题一样——并且在6个月后可以为下一个人或你维护,那么它就没事了:)因为我想知道是否有人想到过这一点,是否有人能看到这样做的任何陷阱