【问题标题】:How to supply a different implementation if the class implements an interface using Laravel's container如果类使用 Laravel 的容器实现接口,如何提供不同的实现
【发布时间】:2017-10-31 19:35:42
【问题描述】:

我正在使用依赖注入来注入 Guzzle 的 HTTP 客户端实例。我有几个调用外部服务的数据提供者类,其中一些需要通过代理进行路由。我有一个在这些类上实现的空接口ConnectViaProxy。我想用代理选项集绑定一个 Guzzle 实例,但我不能使用:

$this->app->when(ConnectViaProxy::class)
    ->needs(GuzzleClient::class)
    ->give(function (): ProxiedGuzzle {
        return new ProxiedGuzzle();
    });

因为when 需要一个具体的类,而不是一个接口。

以下是应代理的提供程序示例:

use GuzzleHttp\Client as GuzzleClient;

class FooProvider implements Provider, ConnectViaProxy
{
    public function __construct(GuzzleClient $client)
    {
        // Should be an instance of ProxiedGuzzle
        dd($client);
    }
}

还有一个不应被代理的提供者示例:

use GuzzleHttp\Client as GuzzleClient;

class BarProvider implements Provider
{
    public function __construct(GuzzleClient $client)
    {
        // Should be an instance of GuzzleClient
        dd($client);
    }
}

这里是ProxiedGuzzle 类:

use GuzzleHttp\Client as GuzzleClient;

class ProxiedGuzzle extends GuzzleClient
{
    public function __construct()
    {
        parent::__construct([
            'proxy' => [
                'http' => PROXY_IP,
                'https' => PROXY_IP,
            ],
        ]);
    }
}

知道我该怎么做吗?

谢谢

【问题讨论】:

    标签: laravel laravel-5 guzzle


    【解决方案1】:

    似乎摆脱这种情况的唯一方法是使用父类。

    /**
    * 
    */
    class ViaProxy implements ConnectViaProxy
    {
    
        public function __construct(GuzzleClient $client)
        {
            // Should be an instance of ProxiedGuzzle
            dd($client);
        }
    }
    

    然后在你需要的时候使用它

    /**
     * 
     */
    class FooProvider extends ViaProxy implements Provider
    {
    
    }
    

    如果不是就不要

    use GuzzleHttp\Client as GuzzleClient;
    /**
     * 
     */
    class BarProvider implements Provider
    {
        public function __construct(GuzzleClient $client)
        {
            // Should be an instance of GuzzleClient
            dd($client);
        }
    

    像往常一样使用上下文绑定

    $this->app->when(ViaProxy::class)
        ->needs(GuzzleClient::class)
        ->give(function (): ProxiedGuzzle {
            return new ProxiedGuzzle();
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-08
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      相关资源
      最近更新 更多