Today written a PHP class for handling multiple HTTP calls asynchronously (current only supports GET, feel free to modify it to support POST and PUT). By saying asynchronous, it can do something like this:
<?php
$caller = new HttpCaller();
$id1 = $caller->prepare($url1);
$id2 = $caller->prepare($url2);
$id3 = $caller->prepare($url3);
// Send all requests and return immediately
$caller->makeCall();
// Doing something else here (fetching data from DB, computing... all sorts of stuff
// Now we need the result for $url2 call, block until $url2 call return, but no need to wait for $url1 or $url3
$result = $caller->fetch($id2);
// Do something with $result and maybe something else
$result = $caller->fetch($id1); // Need the result for $url1 call
// Do something with $result and maybe something else
$result = $caller->fetch($id3);
// Do something with $result
?>
Implementation of HttpCaller:
<?php
class HttpCaller {
private $timeout;
private $mutliCurl;
private $resultCache = array();
public function __construct($timeout = 9999) {
$this->timeout = intval($timeout);
$this->multiCurl = curl_multi_init();
}
public function __destruct() {
curl_multi_close($this->multiCurl);
}
public function prepare($url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, $this->timeout);
curl_multi_add_handle($this->multiCurl, $curl);
return intval($curl);
}
public function makeCall() {
do {
$res = curl_multi_exec($this->multiCurl, $isRunning);
} while ($res == CURLM_CALL_MULTI_PERFORM);
}
public function fetch($id) {
if (isset($this->resultCache[$id])) {
return $this->resultCache[$id];
}
do {
if (curl_multi_select($this->multiCurl) != -1) {
do {
$res = curl_multi_exec($this->multiCurl, $active);
} while ($res == CURLM_CALL_MULTI_PERFORM);
$info = curl_multi_info_read($this->multiCurl);
if ($info) {
if (curl_errno($info["handle"]) !== 0) {
return false;
}
$tmp = intval($info["handle"]);
$this->resultCache[$tmp] = curl_multi_getcontent($info["handle"]);
if ($tmp === $id) {
return $this->resultCache[$id];
}
}
}
} while ($active && $res == CURLM_OK);
}
}
?>