2014-06-24 84 views
5

如果一个类绑定到的IoC ...Laravel:绑定到IoC容器

App::bind('Thing', function() { 
    return new \ThingOne; 
}); 

然后,ThingOne对象将永远,除非你叫App::make('Thing')实例化。这是一件好事。

但是,如果您尝试覆盖绑定:

App::bind('Thing', function() { 
    return new \ThingOne; 
}); 
App::bind('Thing', function() { 
    return new \ThingTwo; 
}); 
App::bind('Thing', function() { 
    return new \ThingThree; 
}); 

...然后ThingTwo对象和ThingThree对象将被实例化(并呼吁它们的构造函数),即使你从来没有所谓App::make('Thing')!这是一件坏事!为什么,以及如何防止这种情况发生? IoC如果不允许我们覆盖绑定,那么我们可以扩展包和什么? (这就是我想要做什么:绑定类国际奥委会我的包,然后实现在其他项目上的包时,可选覆盖它们)

顺便说一句,这种情况是否使用bind()singleton()没有区别。

非常感谢您的任何指导。

+3

你有没有尝试在重新绑定对象之前调用App :: offsetUnset('Thing')? –

+1

@FractalizeR我没有 - 这工作,谢谢! – Leng

+1

欢迎您:) –

回答

4

该问题似乎在rebound方法中的Illuminate\Container\Container中。逻辑上,该方法仅在重新绑定时调用,因此它不是第一次调用,而是称为后续时间。你可以看到这个实例是为反弹回调做准备的。

/** 
* Fire the "rebound" callbacks for the given abstract type. 
* 
* @param string $abstract 
* @return void 
*/ 
protected function rebound($abstract) 
{ 
    $instance = $this->make($abstract); 

    foreach ($this->getReboundCallbacks($abstract) as $callback) 
    { 
     call_user_func($callback, $this, $instance); 
    } 
} 

FractalizeR是正确的,叫App::offsetUnset('Thing') beforing再结合它不会调用__construct方法。

+0

啊,我明白了。感谢您的时间dwenaus,并感谢您和Fractilize的解决方案。 – Leng