Laravel container and shared instances

I am wondering how Laravel distinguishes between singles (shared instances) and specific implementations that can be overwritten inside a container.

There is a binding method in the container that looks like this:

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

It also has a singleton method that calls this function, but with a common argument, $ is always true:

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

The difference is that although both are related in the property $bindings, singleton sets it like this:

[concrete, true]

How does this make it solitary, although if there seems to be no check if it is already installed or not? Nowhere can I find if he is doing anything with the $ shared variable we set.

In addition, there is another property in this class:

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

It would seem logical that the singleton will be here, so what exactly is it

:

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

+4
1

bind() $shared . make() isSahred() , $shared , , true false .

+3

Source: https://habr.com/ru/post/1663314/


All Articles