|
| 1 | +Batch request sending |
| 2 | +===================== |
| 3 | + |
| 4 | +HTTP Client allows sending multiple requests at once using [[\yii\httpclient\Client::batchSend()]] method: |
| 5 | + |
| 6 | +```php |
| 7 | +use yii\httpclient\Client; |
| 8 | + |
| 9 | +$client = new Client(); |
| 10 | + |
| 11 | +$requests = [ |
| 12 | + $client->get('http://domain.com/keep-alive'), |
| 13 | + $client->post('http://domain.com/notify', ['userId' => 12]), |
| 14 | +]; |
| 15 | +$responses = $client->batchSend($requests); |
| 16 | +``` |
| 17 | + |
| 18 | +Particular [transport](usage-transports.md) may benefit from this method usage, allowing to increase the performance. |
| 19 | +Among the built-in transports, only [[\yii\httpclient\CurlTransport]] does this. It allows to send requests in parallel, |
| 20 | +which saves the program execution time. |
| 21 | + |
| 22 | +> Note: only some particular transports allows processing requests at `batchSend()` in special way, which provides some |
| 23 | + benefit. By default transport just sends them one by one without any error or warning thrown. Make sure you have |
| 24 | + configured correct transport for the client, if you wish to achieve performance boost. |
| 25 | + |
| 26 | +`batchSend()` method returns the array of the responses, which keys correspond the ones from array of requests. |
| 27 | +This allows you to process particular request response in easy way: |
| 28 | + |
| 29 | +```php |
| 30 | +use yii\httpclient\Client; |
| 31 | + |
| 32 | +$client = new Client(); |
| 33 | + |
| 34 | +$requests = [ |
| 35 | + 'news' => $client->get('http://domain.com/news'), |
| 36 | + 'friends' => $client->get('http://domain.com/user/friends', ['userId' => 12]), |
| 37 | + 'newComment' => $client->post('http://domain.com/user/comments', ['userId' => 12, 'content' => 'New comment']), |
| 38 | +]; |
| 39 | +$responses = $client->batchSend($requests); |
| 40 | + |
| 41 | +// result of `GET http://domain.com/news` : |
| 42 | +if ($responses['news']->isOk) { |
| 43 | + echo $responses['news']->content; |
| 44 | +} |
| 45 | + |
| 46 | +// result of `GET http://domain.com/user/friends` : |
| 47 | +if ($responses['friends']->isOk) { |
| 48 | + echo $responses['friends']->content; |
| 49 | +} |
| 50 | + |
| 51 | +// result of `POST http://domain.com/user/comments` : |
| 52 | +if ($responses['newComment']->isOk) { |
| 53 | + echo "Comment has been added successfully"; |
| 54 | +} |
| 55 | +``` |
0 commit comments