Last active
May 20, 2025 19:29
-
-
Save missoxd/674ac41d126df4952d3cf4824fbe2bb6 to your computer and use it in GitHub Desktop.
Testing Guzzle cURL Mult Handler with Promises
This file contains hidden or 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 echo clock function. | |
$clock = function ($label) use ($start) { | |
$end = microtime(true); | |
$total = round($end - $start, 2); | |
echo "Execution of [{$label}] = {$total} sec" . PHP_EOL; | |
}; | |
//Create the Guzzle client. | |
$client = new Client([ | |
'base_uri' => 'https://httpstat.us/', | |
'headers' => [ | |
'Accept' => 'text/plain' | |
] | |
]); | |
//Clock. | |
$clock('p1 before'); | |
//Create async requests. | |
$p1 = $client->getAsync('/200?sleep=10000'); | |
$p1->then(function ($value) use ($clock) { | |
//Clock. | |
$clock('p1 then'); | |
/** @var Response $value */ | |
echo $value->getBody()->getContents() . PHP_EOL; | |
flush(); | |
}); | |
//Clock. | |
$clock('p1 after'); | |
$clock('p2 before'); | |
$p2 = $client->getAsync('/201?sleep=2500'); | |
$p2->then(function ($value) use ($clock) { | |
//Clock. | |
$clock('p2 then'); | |
/** @var Response $value */ | |
echo $value->getBody()->getContents() . PHP_EOL; | |
flush(); | |
}); | |
//Clock. | |
$clock('p2 after'); | |
//Wait to see if requests are running (we know that they are not). | |
sleep(5); | |
//Send async requests. | |
try { | |
//Clock. | |
$clock('unwrap before'); | |
unwrap([$p1, $p2]); | |
//Clock. | |
$clock('unwrap after'); | |
} catch (\Throwable $e) {} | |
//Clock. | |
$clock('end'); | |
/* | |
Sample response. | |
Execution of [p1 before] = 0 sec | |
Execution of [p1 after] = 0.01 sec | |
Execution of [p2 before] = 0.01 sec | |
Execution of [p2 after] = 0.01 sec | |
Execution of [unwrap before] = 5.01 sec | |
Execution of [p2 then] = 8.36 sec | |
201 Created | |
Execution of [p1 then] = 15.82 sec | |
200 OK | |
Execution of [unwrap after] = 15.82 sec | |
Execution of [end] = 15.82 sec | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment