jeudi 26 mars 2020

Laravel Auto-resolve (Auto DI) not the same as registered provider

In my Laravel 5.7 project, I'm trying to auto-inject a Guzzle instance in to any controller or service that needs it. It's simply enough to just type-hint the class and have it inject automatically, but I don't have control over its initial state. I want some presets on Guzzle before each constructor receives it.

I created a GuzzleServiceProvider that registers like so: (note: verify=false)

            $this->app->bind('\GuzzleHttp\Client', function () {
                $stack = HandlerStack::create();
                $stack->push(Middleware::retry($this->decider(), $this->delay()));

                return new Client(['handler' => $stack, 'verify' => false]);
            });

This works fine if I use it in a constructor like so:

$client = app()->make('\GuzzleHttp\Client');

It is proven to be an instance of the one registered in the provider because I can dump the $client and see that verify=false. Guzzle defaults to true so this is working.

However when injected as a dependency, verify=true and the handler stack initial settings I made don't have any effect. This is because it's a different instance of Guzzle.

Is there any way for the dependency injection to use the registered instance, rather than creating a new one?

Thanks!



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/39mAoVy
via IFTTT

Aucun commentaire:

Enregistrer un commentaire