Created
February 8, 2017 08:57
-
-
Save wzed/d9273719e54e78da4a6a63d4fc9e2606 to your computer and use it in GitHub Desktop.
GuzzleHttp\Pool example: identifying responses to concurrent async requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); |
It worked for me!
Thanks for your gist 🙏
Omg, life-saver! Thank you!
This just helped me a lot
Thank you!
This helped alot, thank you friend!
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
.
Thank you so much, never noticed of yield key => value
It's soooooo useful!!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great!
It help me so much. Especially the
yeild
usage, it works!yield $searchTerm => function()
Thank you!