2016-12-09 10 views
4

Laravelがシングルトン(共有インスタンス)とコンテナ内部で上書きされる可能性がある具体的な実装を区別する方法は不思議です。Laravelコンテナと共有インスタンス

コンテナは、次のようになりますbindメソッドがあります。

public function singleton($abstract, $concrete = null) 
{ 
    $this->bind($abstract, $concrete, true); 
} 
:それはまた、この関数を呼び出しますが、シングルトンメソッドを持ってい

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); 
    } 
} 

を$共有引数はいつものように真であることと

違いは、両方とも$bindingsプロパティでバインドされていますが、シングルトンは次のように設定されています。

[concrete, true] 

既に設定されているかどうかチェックがないように見える場合、これはどのようにシングルトンにしますか?私たちが設定した$共有変数で何が起きているのかわかりません。

と呼ばれるこのクラスの別のプロパティも存在していることに加えて:

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

はシングルトンがここで終わるすることは論理的と思われるので、正確にbindメソッドのこの

例が何をしますか:

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''で解決するときに実際に' '$ instance''配列プロパティにプッシュされるようです。そしてこれは実際にアレイを実際にチェックします。今私はもっと深く掘り下げることができます。ありがとう! –

関連する問題