PHP中的异步调用

时间:2015-02-22 22:06:50

标签: php asynchronous callback

我有一堆远程内容提供商,其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中异步执行此操作?

1 个答案:

答案 0 :(得分:0)

如果您使用的是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";
}
?>