Difference Between Bind vs Singleton: When and What to Choose?

Hello Artisan

In this tutorial i will explain what is core difference between bind and singleton in laravel. You know that we can bind our classes in service provider. But for doing that we can use bind or singleton. In this tutorial we will try to know that when and why we use bind and singleton in our Laravel app.

Use bind for reusable classes or objects - the object is constructed each time it is called. If you need multiple instances of a class, in this situation use bind.

Use singleton for a class or object that you need access to throughout the application - the object is only constructed once and so retains state throughout execution. If you only need a single, shared, instance of a class, in this situation use singleton.

Let's see the example to better understand.

app\Support\TestClass.php

namespace App\Support;

class TestClass
{
    protected $value = 0;

    public function increase()
    {
        $this->value++;

    return $this->value;
    }
}

 

AppServiceProvider.php

public function register()
{
    $this->app->singleton(
        'test1',
        \App\Support\TestClass::class
    );

    $this->app->bind(
        'test2',
        \App\Support\TestClass::class
    );
}

 

Now run this in Tinker to understand the output.

>>> app('test1')->increase()
=> 1
>>> app('test1')->increase()
=> 2
>>> app('test1')->increase()
=> 3

>>> app('test2')->increase()
=> 1
>>> app('test2')->increase()
=> 1
>>> app('test2')->increase()
=> 1

 

So can I say that bind always creates a new instance? . You could echo something in the __construct function and see that is does echo every time if you use 'bind' and only echo once if you use 'singelton'. Hope you understand this diffrence between bind and singleton.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js