Last active
September 7, 2020 20:01
-
-
Save missoxd/674ac41d126df4952d3cf4824fbe2bb6 to your computer and use it in GitHub Desktop.
Testing Guzzle cURL Mult Handler with Promises
This file contains 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 | |
/** | |
* We are using Guzzle v6. | |
* composer require "guzzlehttp/guzzle=~6.0" | |
*/ | |
//Load composer. | |
require __DIR__ . '/vendor/autoload.php'; | |
//Use statements. | |
use GuzzleHttp\Client; | |
use GuzzleHttp\Psr7\Response; | |
use function GuzzleHttp\Promise\unwrap; | |
//Start the clock. | |
$start = microtime(true); | |
//Create the Guzzle client. | |
$client = new Client([ | |
'base_uri' => 'https://httpstat.us/', | |
'headers' => [ | |
'Accept' => 'text/plain' | |
] | |
]); | |
//Create async requests. | |
$p1 = $client->getAsync('/200?sleep=5000'); | |
$p1->then(function ($value) { | |
/** @var Response $value */ | |
echo $value->getBody()->getContents() . PHP_EOL; | |
flush(); | |
}); | |
$p2 = $client->getAsync('/201?sleep=2500'); | |
$p2->then(function ($value) { | |
/** @var Response $value */ | |
echo $value->getBody()->getContents() . PHP_EOL; | |
flush(); | |
}); | |
//Send async requests. | |
try { | |
unwrap([$p1, $p2]); | |
} catch (\Throwable $e) { | |
} | |
//End clock time. | |
$end = microtime(true); | |
$total = ceil($end - $start); | |
echo "Execution time of script = {$total} sec" . PHP_EOL; | |
/* | |
Sample response. | |
201 Created | |
200 OK | |
Execution time of script = 7 sec | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment