Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Singleton and Instance

Tags:

php

laravel

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?

like image 551
Mostafa Talebi Avatar asked Oct 27 '25 05:10

Mostafa Talebi


1 Answers

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.

like image 198
fideloper Avatar answered Oct 29 '25 18:10

fideloper