The pecl_http extension has a little gem that can be handy at times – HttpRequestPool. Using this, you can send concurrent HTTP requests and can gain efficiency in fetching non-related data at once. For example, from an external source if your application needs to retrieve an user’s profile, their order history and current balance, you can send parallel requests to the API and get everything together.
Here is a simple example code to illustrate that:
1<?php 2 3$endpoint = "http://api.someservice.com"; 4$userId = 101; 5 6$urls = array( 7 $endpoint . '/profile/' . $userId, 8 $endpoint . '/orderHistory/' . $userId, 9 $endpoint . '/currentBalance/' . $userId10);11 12$pool = new HttpRequestPool;13 14foreach ($urls as $url) {15 $req = new HttpRequest($url, HTTP_METH_GET);16 $pool->attach($req);17}18 19// send all the requests. control is back to the script once 20// all the requests are complete or timed out21$pool->send();22 23foreach ($pool as $request) {24 echo $request->getUrl(), PHP_EOL;25 echo $request->getResponseBody(), PHP_EOL . PHP_EOL;26}