Say you’re pooling requests in Guzzle and want the responses to have access to data such as the request URL. Guzzle doesn’t currently allow for this but that’s all fixed with the help of a simple middleware class.
Usage
When requesting a URL with GuzzleHttp\Client, pass a RESPONSE_META array in your requests second argument like so:
1 2 3 4 5 6 | $client->get($url, [ 'RESPONSE_META' => [ 'url' => $url, 'some_data' => 'foo', ], ]); |
The data is attached as a header to the response. Access it like so: (Remembering to prepend X-GUZZLE-META- to your key)
1 | $some_data = $response->getHeaderLine('X-GUZZLE-META-some_data'); |
Complete Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | $names = ['Alpha', 'Beta', 'Charlie', 'Delta']; $stack = GuzzleHttp\HandlerStack::create(); $stack->push(GuzzleResponseMetaMiddleware::middleware());$client = new GuzzleHttp\Client([ 'handler' => $stack]); $requests = function() use ($client, $names) { foreach ( $names as $name ) { $url = "Http://mydomain.com/?name=".$name; yield function() use ($client, $url, $name) { return $client->getAsync($url, [ 'RESPONSE_META' => [ 'url' => $url, 'name' => $name, ], ]); }; } }; $pool = new GuzzleHttp\Pool($client, $requests(), [ 'concurrency' => 5, 'fulfilled' => function (Psr\Http\Message\ResponseInterface $response, $index) { $url = $response->getHeaderLine('X-GUZZLE-META-url'); $name = $response->getHeaderLine('X-GUZZLE-META-name'); // do something with this info }, ]); // Initiate the transfers and create a promise $promise = $pool->promise(); // Force the pool of requests to complete. $promise->wait(); |