Symfony HttpClient Async example
<?php | |
$client = \Symfony\Component\HttpClient\HttpClient::create(); | |
// Create a few requests: this is entierely async, requests are launched in the background | |
$request1 = $client->request('GET', 'http://releases.ubuntu.com/18.04.2/ubuntu-18.04.2-desktop-amd64.iso?request=a'); | |
$request2 = $client->request('GET', 'http://releases.ubuntu.com/18.04.2/ubuntu-18.04.2-desktop-amd64.iso?request=b'); | |
$request3 = $client->request('GET', 'http://releases.ubuntu.com/18.04.2/ubuntu-18.04.2-desktop-amd64.iso?request=c'); | |
// The code continues execution immediatly, you can do whathever you want here ... | |
// Now if you call getContent or getStatusCode on one of the requests, you will get a blocking wait | |
// for this specific request: $request1->getContent(); would only wait for request 1, if request 2 & 3 | |
// take mucher longer we wouldn't wait for them now. | |
// But to achieve real async, you can go even further and use stream(): | |
// Infinite loop, for instance an event-loop | |
while (true) { | |
// Create an iterable stream for all the requests | |
// A timeout of 0 means don't wait any requests and give me only the responses chunks which are ready right now | |
$stream = $client->stream([$request1, $request2, $request3], 0); | |
foreach ($stream as $response => $chunk) { | |
if ($chunk->isTimeout()) { | |
echo 'Chunk received from response '.$response->getInfo('url')."\n"; | |
} | |
} | |
// Chunking with stream() also means support for HTTP2 push out of the box | |
// Code here will be executed regularly, between the chunks arriving in the background ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment