Laravel容器和共享实例

时间:2016-12-09 10:34:17

标签: php laravel oop laravel-5 containers

我想知道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);
    }
}

它还有一个调用此函数的单例方法,但$ shared参数始终为true,如下所示:

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

1 个答案:

答案 0 :(得分:3)

bind()方法可以保存$shared here。然后是make() method is using isSahred()方法,用于检查是否$shared is set,然后检查是true还是false here