In Laravel Documentation I have read:
Binding A "Shared" Type Into The Container
App::singleton('foo', function()
{
return new FooBar;
});
Vs.
Binding An Existing Instance Into The Container
$foo = new Foo;
App::instance('foo', $foo);
Due to the weakness of Laravel Documentation I cannot understand what is their difference.
Can anyone explain me?
Checking in on Github, we can see that the singleton method is a alias for the bind method, but set to be "shared" (basically, a singleton):
/**
* Register a shared binding in the container.
*
* @param string $abstract
* @param Closure|string|null $concrete
* @return void
*/
public function singleton($abstract, $concrete = null)
{
return $this->bind($abstract, $concrete, true);
}
On the other hand, the instance method, it turns out, has a fairly simple use case:
/**
* Register an existing instance as shared in the container.
*
* @param string $abstract
* @param mixed $instance
* @return void
*/
public function instance($abstract, $instance) { ... }
Basically you're passing in an existing object/value, rather than a Closure which returns an object/value. It returns that same object/value instance, which is effectively a singleton as well.
The difference is that an instance already exists when its bound to the container when using "instance", while its not yet created (it's lazy-loaded, thus saving potentially expensive operations until needed) via "singleton", when you pass in a closure who's responsibility is to produce the resulting object/value singleton.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With