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() {}
}
*/