为什么要在laravel的服务容器上使用单例方法?

时间:2019-08-22 22:22:29

标签: php laravel service containers

我是Laravel的新手,而我现在刚进入Service Container部分。阅读后,我无法理解使用 Singleton 绑定和 Simple 绑定(分别为$app->singleton()$app->bind())之间的区别。 如果我需要将服务用作单例,那么我的服务不是单例吗?

// 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'));
});

这就是我的意思:

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

0 个答案:

没有答案