Set request parameters after initialization in guzzle 6

In Guzzle with version <6, I used to set my authentication header on the fly after initializing the client. For this, I used setDefaultOption() .

 $client = new Client(['base_url' => $url]); $client->setDefaultOption('auth', [$username, $password]); 

However, this feature seems to be deprecated in version 6. How do I do this?

Note. The reason I need to do this is because I use buzzing for batch requests, where some requests require different authentication parameters.

+7
php guzzle
source share
2 answers

The best option for Guzzle 6+ is to recreate the Client. The GUZLE HTTP client is now immutable, so whenever you want to change something, you must create a new object.

This does not mean that you need to recreate the entire graph of objects, HandlerStack and middlewares can remain unchanged:

 use GuzzleHttp\Client; use GuzzleHttp\HandlerStack; $stack = HandlerStack::create(); $stack->push(Middleware::retry(/* ... */)); $stack->push(Middleware::log(/* ... */)); $client = new Client([ 'handler' => $stack, 'base_url' => $url, ]); // ... $newClient = new Client([ 'handler' => $stack, 'base_url' => $url, 'auth' => [$username, $password] ]); 
+3
source share

You can send the parameter "auth" when creating a client or sending a request.

 $client = new Client(['base_url' => $url, 'auth' => ['username', 'password', 'digest']]); 

OR

 $client->get('/get', ['auth' => ['username', 'password', 'digest']]); 

Another way is to rewrite the requestAsync method and add your own logic to it. But there is no reason for this.

+1
source share

All Articles