Skip to content

Instantly share code, notes, and snippets.

@sidigi
Forked from yched/index.php
Created December 2, 2022 09:58
Show Gist options
  • Save sidigi/d2b7c8234b5781d903ed8faf71da5af4 to your computer and use it in GitHub Desktop.
Save sidigi/d2b7c8234b5781d903ed8faf71da5af4 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