Skip to content

Instantly share code, notes, and snippets.

@yched
Last active November 1, 2017 15:32
Show Gist options
  • Save yched/aef9df44c383ea00d345f8416e78e406 to your computer and use it in GitHub Desktop.
Save yched/aef9df44c383ea00d345f8416e78e406 to your computer and use it in GitHub Desktop.
Coroutines Guzzle (class)
<?php
// composer require guzzlehttp/guzzle
include ('./vendor/autoload.php');
use GuzzleHttp\Client;
use GuzzleHttp\Promise;
use GuzzleHttp\Psr7\Request;
$client = new DomainClient(new Client());
$service = new MyService($client);
$promises = [
'foo' => $service->doStuffAsync('foo'),
'bar' => $service->doStuffAsync('bar'),
];
$results = Promise\settle($promises)->wait();
println('-----------');
array_walk($results, function ($result, $key) {
println("result $key : $result[value]");
});
class MyService {
function __construct($client)
{
$this->client = $client;
}
/**
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function doStuffAsync($name, $recurse = TRUE)
{
return Promise\coroutine(function() use ($name, $recurse) {
$sum = 0;
for ($i = 1; $i <= 5; $i++) {
// Démo : coroutines imbriquées.
if ($i == 3 && $recurse) {
$sum += yield $this->doStuffAsync($name . '-inner', FALSE);
continue;
}
$result = yield $this->client->getResultAsync($name, $i, rand(0, 5));
$sum += $result;
println("$name : $result");
}
// Résultat attendu :
// - coroutines internes : 1 + 2 + 3 + 4 + 5 = 15
// - coroutines externes : 1 + 2 + 15 + 4 + 5 = 27
yield $sum;
});
}
}
class DomainClient {
public function __construct(Client $client)
{
$this->client = $client;
}
/**
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function getResultAsync($name, $value, $delay) {
return Promise\coroutine(function () use ($name, $value, $delay) {
// On simule de la latence avec http://httpbin.org/delay
$req = new Request('GET',"http://httpbin.org/delay/$delay?name=$name&value=$value");
/* @var $res \GuzzleHttp\Psr7\Response */
$res = yield $this->client->sendAsync($req);
$data = json_decode((string) $res->getBody(), TRUE);
yield $data['args']['value'];
});
}
}
function println($string) {
echo "$string\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment