Skip to content

Instantly share code, notes, and snippets.

@yched
Last active February 7, 2023 12:23
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yched/9aa2bf5e30fa764c646e9f7f9606835c to your computer and use it in GitHub Desktop.
Save yched/9aa2bf5e30fa764c646e9f7f9606835c to your computer and use it in GitHub Desktop.
Coroutines Guzzle
<?php
// composer require guzzlehttp/guzzle
include ('./vendor/autoload.php');
use GuzzleHttp\Client;
use GuzzleHttp\Promise;
use GuzzleHttp\Psr7\Request;
$promises = [
'task1' => task1Async(),
'task2' => task2Async(),
];
$results = Promise\settle($promises)->wait();
println('-----------');
array_walk($results, function ($result, $key) {
println("result $key : $result[value]");
});
/**
* @return \GuzzleHttp\Promise\PromiseInterface
*/
function task1Async() {
return Promise\coroutine(function () {
$sum = 0;
println("task1 : start 1");
$result = yield getResultAsync('task1', 1, 3);
println("task1 : end 1 (result $result)");
$sum += $result;
println("task1 : start 2");
$result = yield getResultAsync('task1', 2, 0);
println("task1 : end 2 (result $result)");
$sum += $result;
yield $sum;
});
}
/**
* @return \GuzzleHttp\Promise\PromiseInterface
*/
function task2Async() {
return Promise\coroutine(function () {
$sum = 0;
println("task2 : start 1");
$result = yield getResultAsync('task2', 1, 0);
println("task2 : end 1 (result $result)");
$sum += $result;
println("task2 : start 2");
$result = yield getResultAsync('task2', 2, 4);
println("task2 : end 2 (result $result)");
$sum += $result;
yield $sum;
});
}
/**
* @return \GuzzleHttp\Promise\PromiseInterface
*/
function getResultAsync($name, $value, $delay) {
return Promise\coroutine(function () use ($name, $value, $delay) {
$req = new Request('GET', "http://httpbin.org/delay/$delay?name=$name&value=$value");
/* @var $res \GuzzleHttp\Psr7\Response */
$res = yield client()->sendAsync($req);
$data = json_decode($res->getBody()->getContents(), true);
yield $data['args']['value'];
});
}
/**
* @return \GuzzleHttp\Client
*/
function client() {
static $client;
$client = $client ?? new Client();
return $client;
}
function println($string) {
echo "$string\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment