1<?php
2
3/**
4 * This example demonstrates the ability for clients to work asynchronously.
5 *
6 * By default up to 10 requests will be executed in paralel. HTTP connections
7 * are re-used and DNS is cached, all thanks to the power of curl.
8 *
9 * @copyright Copyright (C) 2009-2015 fruux GmbH (https://fruux.com/).
10 * @author Evert Pot (http://evertpot.com/)
11 * @license http://sabre.io/license/ Modified BSD License
12 */
13use Sabre\HTTP\Request;
14use Sabre\HTTP\Client;
15
16// Find the autoloader
17$paths = [
18    __DIR__ . '/../vendor/autoload.php',
19    __DIR__ . '/../../../autoload.php',
20    __DIR__ . '/vendor/autoload.php',
21
22];
23
24foreach ($paths as $path) {
25    if (file_exists($path)) {
26        include $path;
27        break;
28    }
29}
30
31// This is the request we're repeating a 1000 times.
32$request = new Request('GET', 'http://localhost/');
33$client = new Client();
34
35for ($i = 0; $i < 1000; $i++) {
36
37    echo "$i sending\n";
38    $client->sendAsync(
39        $request,
40
41        // This is the 'success' callback
42        function($response) use ($i) {
43            echo "$i -> " . $response->getStatus() . "\n";
44        },
45
46        // This is the 'error' callback. It is called for general connection
47        // problems (such as not being able to connect to a host, dns errors,
48        // etc.) and also cases where a response was returned, but it had a
49        // status code of 400 or higher.
50        function($error) use ($i) {
51
52            if ($error['status'] === Client::STATUS_CURLERROR) {
53                // Curl errors
54                echo "$i -> curl error: " . $error['curl_errmsg'] . "\n";
55            } else {
56                // HTTP errors
57                echo "$i -> " . $error['response']->getStatus() . "\n";
58            }
59        }
60    );
61}
62
63// After everything is done, we call 'wait'. This causes the client to wait for
64// all outstanding http requests to complete.
65$client->wait();
66