Skip to content

Instantly share code, notes, and snippets.

@hungthai1401
Forked from wzed/guzzle_pool_example.php
Created March 21, 2023 07:59
Show Gist options
  • Save hungthai1401/aaa1ef38b3b25ed76f0f1ec4a9bf779d to your computer and use it in GitHub Desktop.
Save hungthai1401/aaa1ef38b3b25ed76f0f1ec4a9bf779d 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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment