mardi 31 octobre 2017

How to supply a different implementation if the class implements an interface using Laravel's container

I’m using dependency injection to inject instances of Guzzle’s HTTP client. I have several data provider classes that call external services, some of which needs to be routed through proxies. I have an empty interface ConnectViaProxy that is implemented on those classes. I want to bind a Guzzle instance with the proxy option set, but I can’t use:

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

Because when requires a concrete class, not an interface.

Here is an example of a provider that should be proxied:

use GuzzleHttp\Client as GuzzleClient;

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

And an example of a provider that shouldn't be proxied:

use GuzzleHttp\Client as GuzzleClient;

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

And here is the ProxiedGuzzle class:

use GuzzleHttp\Client as GuzzleClient;

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

Any idea how I could do this?

Thanks



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2lxdjfy
via IFTTT

Aucun commentaire:

Enregistrer un commentaire