Monday, December 7, 2020

Laravel singleton vs bind

 Use bind for reusable classes or objects - the object is constructed each time it is called. If you need multiple instances of a class, 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, use singleton

For example:

app\Support\TestClass.php

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

Tinker:

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

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