PHP中的异步调用


Asynchronous calls in PHP

我有一群远程内容提供商,他们的API被查询以响应用户请求。假设每个内容提供商都需要被查询,我将如何异步发出API请求并收集结果?现在,我只是在我的内容提供商集合上迭代,并一个接一个地调用他们的API,如下所示:

/**
 * A wrapper method that delegates requests to content providers.
 */
public function __call($name, $args) {
    // do stuff before
    $results = array();
    foreach ($contentProviders as $contentProvider) {
        $callback = array($contentProvider, $name), $args);
        $results[get_class($contentProvider)] = call_user_func_array($callback);
    }
    // do stuff after
    // build final result from individual calls
    return $result;
}

然而,这让我等到一个请求完成后再开始下一个请求。有没有一种方法可以在PHP中异步实现这一点?

如果你正在使用PHP5,Wez Furlong的这篇文章可能会帮助你:http://wezfurlong.org/blog/2005/may/guru-multiplexing/

上述页面的示例代码:

<?php
$hosts = array("host1.sample.com", "host2.sample.com", "host3.sample.com");
$timeout = 15;
$status = array();
$sockets = array();
/* Initiate connections to all the hosts simultaneously */
foreach ($hosts as $id => $host) {
    $s = stream_socket_client("$host:80", $errno, $errstr, $timeout, 
        STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT);
    if ($s) {
        $sockets[$id] = $s;
        $status[$id] = "in progress";
    } else {
        $status[$id] = "failed, $errno $errstr";
    }
}
/* Now, wait for the results to come back in */
while (count($sockets)) {
    $read = $write = $sockets;
    /* This is the magic function - explained below */
    $n = stream_select($read, $write, $e = null, $timeout);
    if ($n > 0) {
        /* readable sockets either have data for us, or are failed
         * connection attempts */
        foreach ($read as $r) {
            $id = array_search($r, $sockets);
            $data = fread($r, 8192);
            if (strlen($data) == 0) {
                if ($status[$id] == "in progress") {
                    $status[$id] = "failed to connect";
                }
                fclose($r);
                unset($sockets[$id]);
            } else {
                $status[$id] .= $data;
            }
        }
        /* writeable sockets can accept an HTTP request */
        foreach ($write as $w) {
            $id = array_search($w, $sockets);
            fwrite($w, "HEAD / HTTP/1.0''r''nHost: "
                . $hosts[$id] .  "''r''n''r''n");
            $status[$id] = "waiting for response";
        }
    } else {
        /* timed out waiting; assume that all hosts associated
         * with $sockets are faulty */
        foreach ($sockets as $id => $s) {
            $status[$id] = "timed out " . $status[$id];
        }
        break;
    }
}
foreach ($hosts as $id => $host) {
    echo "Host: $host''n";
    echo "Status: " . $status[$id] . "''n''n";
}
?>