Last active
June 17, 2019 04:59
-
-
Save ardani/8b4dfa923f1f43bf62f4f8bf76b19755 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
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