PHP code example of bluepsyduck / multicurl

1. Go to this page and download the library: Download bluepsyduck/multicurl library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

bluepsyduck / multicurl example snippets




use BluePsyduck\MultiCurl\MultiCurlManager;
use BluePsyduck\MultiCurl\Entity\Request;

$manager = new MultiCurlManager();

$requestFoo = new Request();
$requestFoo->setUrl('http://localhost/data.php?action=foo');
$manager->addRequest($requestFoo); // Will execute the first request, but will not wait for it to finish.

$requestBar = new Request();
$requestBar->setUrl('http://localhost/data.php?action=bar');

$manager->addRequest($requestBar); // Will execute the second request, having both run parallel.

// Some other code.

$manager->waitForAllRequests(); // Will wait for both requests to be finished.

// Do something with the responses
var_dump($requestFoo->getResponse());
var_dump($requestBar->getResponse());

 

use BluePsyduck\MultiCurl\MultiCurlManager;
use BluePsyduck\MultiCurl\Entity\Request;

$manager = new MultiCurlManager();
$manager->setNumberOfParallelRequests(4); // Limit number of parallel requests.

for ($i = 0; $i < 16; ++$i) {
    $request = new Request();
    $request->setUrl('http://localhost/data.php?i=' . $i);
    $request->setOnInitializeCallback(function(Request $request) use ($i) {
        echo 'Initialize #' . $i . PHP_EOL;
    });
    $request->setOnCompleteCallback(function(Request $request) use ($i) {
        echo 'Complete #' . $i . PHP_EOL;
    });
    $manager->addRequest($request);
}

// Now 16 requests have been scheduled to be executed, but only 4 requests will run in parallel.
// Once a request finishes, the next one will be executed.

$importantRequest = new Request();
$importantRequest->setUrl('http://localhost/data.php?type=important');
$importantRequest->setOnInitializeCallback(function(Request $request) use ($i) {
    echo 'Initialize important request' . PHP_EOL;
});
$importantRequest->setOnCompleteCallback(function(Request $request) use ($i) {
    echo 'Complete important request' . PHP_EOL;
});
$manager->addRequest($importantRequest); // Important request will not be executed because of the limit.

$manager->waitForSingleRequest($importantRequest); // This will execute the request, ignoring the limit.
// So now actually 5 requests are running in parallel.

echo 'Important request has finished.' . PHP_EOL;

$manager->waitForAllRequests(); // Wait for all the other requests.