1

I'm new in Laravel and I'm just right now with Service Container section. Reading it I can't understand what is the difference between using Singleton binding and Simple binding ($app->singleton() and $app->bind() respectively). If I need to use a service as a singleton, whý my service is not a singleton?

// https://laravel.com/docs/5.8/container

// Simple binding:
$this->app->bind('HelpSpot\API', function ($app) {
    return new HelpSpot\API($app->make('HttpClient'));
});
// Binding singleton:
$this->app->singleton('HelpSpot\API', function ($app) {
    return new HelpSpot\API($app->make('HttpClient'));
});

That's what I mean:

// Binding singleton with simple binding method but using singleton class:
$this->app->bind('HelpSpot\API', function ($app) {
    return HelpSpot\API::getInstance($app->make('HttpClient'));
});

/*
namespace HelpSpot;

final class HttpClient {

}
final class API {

    private static $instance;

    private function __construct(HttpClient $httpClient) {
        $this->httpClient = $httpClient;
    }
    public static function getInstance(HttpClient $httpClient) {
        if ( ! self::$instance instanceof API ) {
            self::$instance = new API($httpClient);
        }
        return self::$instance;
    }

    private function __clone() {}
}
*/
dparoli
  • 8,891
  • 1
  • 30
  • 38
AzuraStar
  • 31
  • 4
  • This may be what you want. [https://stackoverflow.com/questions/25229064/laravel-difference-appbind-and-appsingleton](https://stackoverflow.com/questions/25229064/laravel-difference-appbind-and-appsingleton) – Puckwang Aug 22 '19 at 23:27
  • @Puckwang, thanks for your reply but I'm still having the same question " If I need to use a service as a singleton, whý my service is not a singleton?" – AzuraStar Aug 31 '19 at 10:36

0 Answers0