Skip to content

Instantly share code, notes, and snippets.

@wzed
Created February 8, 2017 08:57
Show Gist options
  • Star 32 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save wzed/d9273719e54e78da4a6a63d4fc9e2606 to your computer and use it in GitHub Desktop.
Save wzed/d9273719e54e78da4a6a63d4fc9e2606 to your computer and use it in GitHub Desktop.
GuzzleHttp\Pool example: identifying responses to concurrent async requests
<?php
/*
* Using a key => value pair with the yield keyword is
* the cleanest method I could find to add identifiers or tags
* to asynchronous concurrent requests in Guzzle,
* so you can identify which response is from which request!
*/
$client = new GuzzleHttp\Client(['base_uri' => 'http://httpbin.org']);
$requestGenerator = function($searchTerms) use ($client) {
foreach($searchTerms as $searchTerm) {
// The magic happens here, with yield key => value
yield $searchTerm => function() use ($client, $searchTerm) {
// Our identifier does not have to be included in the request URI or headers
return $client->getAsync('/get?q='.$searchTerm, ['headers' => ['X-Search-Term' => $searchTerm]]);
};
}
};
$searchTerms = ['apple','banana','pear','orange','melon','grape','raisin'];
$pool = new GuzzleHttp\Pool($client, $requestGenerator($searchTerms), [
'concurrency' => 3,
'fulfilled' => function(GuzzleHttp\Psr7\Response $response, $index) {
// This callback is delivered each successful response
// $index will be our special identifier we set when generating the request
$json = json_decode((string)$response->getBody());
// If these values don't match, something is very wrong
echo "Requested search term: ", $index, "\n";
echo "Parsed from response: ", $json->headers->{'X-Search-Term'}, "\n\n";
},
'rejected' => function(Exception $reason, $index) {
// This callback is delivered each failed request
echo "Requested search term: ", $index, "\n";
echo $reason->getMessage(), "\n\n";
},
]);
// Initiate the transfers and create a promise
$promise = $pool->promise();
// Force the pool of requests to complete
$promise->wait();
@DazDotOne
Copy link

Amazing!

Thanks for the gist

@var618
Copy link

var618 commented Mar 25, 2020

Great!
It help me so much. Especially the yeild usage, it works!
yield $searchTerm => function()

Thank you!

@johnyejin
Copy link

It worked for me!
Thanks for your gist 🙏

@blueskies79
Copy link

Omg, life-saver! Thank you!

@xPabu
Copy link

xPabu commented Apr 1, 2022

This just helped me a lot
Thank you!

@Zerenty
Copy link

Zerenty commented Aug 19, 2022

This helped alot, thank you friend!

@mohachi
Copy link

mohachi commented Feb 16, 2023

Its not clearly mentioned in the docs that the $requests param of the Pool constructor can be an Iterator or an array of type PromiseInterface.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment