Laravel: 服务容器实例的不同实现

Laravel: Different implementations on an instance with Servcie Container

在 Laravel 中,如何使用 Laravel 的服务容器 (https://laravel.com/docs/5.7/container).

解析一个实例的 2 个不同的单例实现

例如,我对 Foo class 的 2 个实现是:

$this->app->singleton(Foo::class, function ($app) {
    return new Foo(config('services.foo.apiKey1'));
});

$this->app->singleton(Foo::class, function ($app) {
    return new Foo(config('services.foo.apiKey2'));
});

然后我也必须以某种方式解决它:

$fooV1 = app(Foo::class); // ?
$fooV2 = app(Foo::class); // ?

编写和解析实例的 2 个不同单例实现的正确方法是什么?

更新

我试过的一种解决方案如下:

$this->app->singleton(Foo::class, function ($app, $parameters) {
    dump('Creating...'); // For testing only to see is actually a singleton
    $apiKey = $parameters[0] ? config('services.foo.apiKey1') : config('services.foo.apiKey2');
    return new Foo($apiKey);
});

然后像这样解决:

$fooV1 = app(Foo::class, [true]);
$fooV2 = app(Foo::class, [false]);

上面也正确输出:

Creating...
Creating...

因为这是 2 个不同的单例。

这在大多数情况下都有效。但是,单例方面不受尊重。即当创建相同的 foo 两次时:

$aV1 = app(Foo::class, [true]);
$bV1 = app(Foo::class, [true]);

输出:

Creating...
Creating...

在这种情况下它应该只输出一次Created...,因为已经创建了具有相同参数集的Foo,因此不是单例。

绑定单例

   $this->app->singleton('foo1', function ($app) {
     return new Foo(config('services.foo.apiKey1'));
   });

    $this->app->singleton('foo2', function ($app) {
        return new Foo(config('services.foo.apiKey2'));
     });

不是在第一个参数上传递 Foo::class,而是传递您将用来解析您正在创建的单例的名称

要解决,请执行以下操作

//a new instance of Foo is created 
$foo1 = $this->app->make('foo1'); 

//the same instance created before is returned
$foo2 = $this->app->make('foo2');

如有帮助请告诉我