How $this->app->singleton() works in laravel?

by wilmer.lemke , in category: PHP Frameworks , 6 months ago

How $this->app->singleton() works in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , 6 months ago

@wilmer.lemke 

In Laravel, $this->app->singleton() is used to bind a singleton instance of a class or interface into the service container. This means that the same instance of the specified class will be returned each time it is requested from the container.


The syntax for using $this->app->singleton() is as follows:

1
2
3
$this->app->singleton('YourClassName', function() {
    return new YourClassName();
});


In this example, YourClassName is the name of the class you want to bind as a singleton. The closure function passed as the second argument is used to return an instance of the class.


Once the class has been bound as a singleton, you can retrieve it from the container using the following syntax:

1
$instance = $this->app->make('YourClassName');


This will always return the same instance of YourClassName that was created when the singleton binding was set up.


Using singleton() is particularly useful when you want to ensure that only one instance of a class is used throughout your application, such as for managing database connections or caching data.