phpguzzleguzzle6

How do I configure default query parameters with Guzzle 6?


Migrating from 5 to 6, and I've run into a snag and can't find the relevant docs.

Guzzle docs here, http://guzzle.readthedocs.io/en/latest/quickstart.html#creating-a-client, site that we can add "any number of default request options".

I want to send "foo=bar" with every request. E.g.:

$client = new Client([
    'base_uri' => 'http://google.com',
]);

$client->get('this/that.json', [
    'query' => [ 'a' => 'b' ],
]);

This will generate GET on http://google.com/this/that.json?a=b

How do I modify the client construction so that it yields:

http://google.com/this/that.json?foo=bar&a=b

Thanks for your help!


Solution

  • Alright, so far, this works here:

            $extraParams = [
                'a' => $config['a'],
                'b' => $config['b'],
            ];
    
            $handler = HandlerStack::create();
            $handler->push(Middleware::mapRequest(function (RequestInterface $request) use ($extraParams) {
    
                $uri  = $request->getUri();
                $uri .= ( $uri ? '&' : '' );
                $uri .= http_build_query( $extraParams );
    
                return new Request(
                    $request->getMethod(),
                    $uri,
                    $request->getHeaders(),
                    $request->getBody(),
                    $request->getProtocolVersion()
                );
            }));
    
            $this->client = new Client([
                'base_uri' => $url,
                'handler' => $handler,
                'exceptions' => false,
            ]);
    

    If anyone knows how to make it less sinister-looking, I would say thank you!