Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set request options after initialisation in guzzle 6

Tags:

php

guzzle

In Guzzle with version < 6 I used to set my authentication header on the fly after the initialisation of the client. I used setDefaultOption() for this.

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

However this functionality seems to be deprecated in version 6. How would I go about this?

Note: the reason I need to do it this way is because I'm using guzzle for batch requests where some requests need different authentication parameters.

like image 993
tomvo Avatar asked Jul 24 '15 11:07

tomvo


2 Answers

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

This doesn't mean that you have to recreate the whole object graph, HandlerStack and middlewares can stay the same:

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]
]);
like image 85
Alexey Shokov Avatar answered Nov 09 '22 18:11

Alexey Shokov


You can send the 'auth' param, while constructing the client or sending the request.

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

OR

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

The other way is to rewrite the requestAsync method and add your custom logic in it. But there is no reason for that.

like image 2
pavkatar Avatar answered Nov 09 '22 17:11

pavkatar