Skip to content

Instantly share code, notes, and snippets.

@ardani
Last active June 17, 2019 04:59
Show Gist options
  • Save ardani/8b4dfa923f1f43bf62f4f8bf76b19755 to your computer and use it in GitHub Desktop.
Save ardani/8b4dfa923f1f43bf62f4f8bf76b19755 to your computer and use it in GitHub Desktop.
<?php
use GuzzleHttp\Promise\EachPromise;
use GuzzleHttp\Promise\FulfilledPromise;
use GuzzleHttp\Psr7\Response;
use Cache;
$users = ['one', 'two', 'three'];
$cache = new Cache();
$promises = (function () use ($users, $cache) {
foreach ($users as $user) {
// check cache is exist
if ($cache->hasItem('cache_user_' . $user)) {
$profile = $cache->getItem($user)->get();
yield new FulfilledPromise($profile);
continue;
}
// don't forget using generator
yield $this->getAsync('https://api.demo.com/v1/users?username=' . $user)
->then(function (Response $response) use ($cache, $user) {
$profile = json_decode($response->getBody(), true);
// save to cache expiry to 300s
$cache->put('cache_user_' . $user, $profile, $expiry = 300);
return $profile;
});
}
})();
$eachPromise = new EachPromise($promises, [
// how many concurrency we are use
'concurrency' => 4,
'fulfilled' => function ($profile) {
// process object profile of user here
},
'rejected' => function ($reason) {
// handle promise rejected here
}
]);
$eachPromise->promise()->wait();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment