【问题标题】:Laravel container and shared instancesLaravel 容器和共享实例
【发布时间】:2016-12-09 10:34:16
【问题描述】:

我想知道 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 参数总是这样:

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

【问题讨论】:

    标签: php laravel oop laravel-5 containers


    【解决方案1】:

    bind() 方法保存$shared here。然后make() method is using isShared()方法检查$sharedis set,然后检查它是true还是falsehere

    【讨论】:

    • 谢谢,这让我更近了一步,似乎在使用make 解析时,作为单例的共享绑定实际上被推入了$instance 数组属性。这实际上是事先检查数组。我现在可以深入研究了。谢谢!
    猜你喜欢
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-22
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多