2016-12-09 57 views
4

我想知道Laravel如何区分单例(共享实例)和可能在容器中被覆盖的具体实现。Laravel容器和共享实例

容器具有绑定方法,看起来像这样:

public function bind($abstract, $concrete = null, $shared = false) 
{   
    // If no concrete type was given, we will simply set the concrete type to the 
    // abstract type. After that, the concrete type to be registered as shared 
    // without being forced to state their classes in both of the parameters. 
    $this->dropStaleInstances($abstract); 

    if (is_null($concrete)) { 
     $concrete = $abstract; 
    } 

    // If the factory is not a Closure, it means it is just a class name which is 
    // bound into this container to the abstract type and we will just wrap it 
    // up inside its own Closure to give us more convenience when extending. 
    if (!$concrete instanceof Closure) { 
     $concrete = $this->getClosure($abstract, $concrete); 
    } 

    $this->bindings[$abstract] = compact('concrete', 'shared'); 

    // If the abstract type was already resolved in this container we'll fire the 
    // rebound listener so that any objects which have already gotten resolved 
    // can have their copy of the object updated via the listener callbacks. 
    if ($this->resolved($abstract)) { 
     $this->rebound($abstract); 
    } 
} 

它还具有调用此功能,但一个单身方法与$共享参数始终是真实的,像这样:

public function singleton($abstract, $concrete = null) 
{ 
    $this->bind($abstract, $concrete, true); 
} 

这里的区别在于,虽然他们都绑定在$bindings属性中,但单身人士设置它像这样:

[concrete, true] 

这是如何使它成为一个单身,但如果似乎没有检查,如果它已被设置或没有?我无处可查找它是否对我们设置的$ shared变量做任何事情。

除此之外也有叫这个班另一个属性:

/** 
* The container's shared instances. 
* 
* @var array 
*/ 
protected $instances = []; 

这似乎合乎逻辑的单身到这里就结束了,所以这究竟

绑定方法示例:

https://github.com/laravel/framework/blob/5.3/src/Illuminate/Container/Container.php#L178

回答

3

bind()方法保存$sharedhere。然后make() method is using isSahred()方法检查是否$sharedis set然后检查它是否是truefalsehere

+1

感谢,让我更近了一步,似乎共享绑定单身实际上被''''''''''make'解析时被推入到''''''''''数组属性中。事实上,这事先检查数组。现在我可以深入研究。谢谢! –