symfony2中的异步调用

时间:2016-04-20 15:21:48

标签: php symfony asynchronous

如何在symfony2.7 Like中异步调用方法。

我必须检索4个不同API连接的数据。问题是我的应用程序响应缓慢,因为PHP是同步的,所以它必须等待所有API的响应然后呈现数据。

class MainController{

    public function IndexAction(){
    // make Asynchronous Calls to GetFirstAPIData(),  GetSecondAPIData(), GetThridAPIData()
  }
    public function GetFirstAPIData(){
    // Get data
  }

    public function GetSecondAPIData(){
    // Get data
  }

    public function GetThridAPIData(){
    // Get data
  }
}

1 个答案:

答案 0 :(得分:2)

您可以使用guzzle,尤其是当我们谈论基于http的apis时。 Guzzle是一个内置异步调用的Web客户端。

代码看起来有点像这样:(取自docs

$client = new Client(['base_uri' => 'http://httpbin.org/']);

// Initiate each request but do not block
$promises = [
    'image' => $client->getAsync('/image'),
    'png'   => $client->getAsync('/image/png'),
    'jpeg'  => $client->getAsync('/image/jpeg'),
    'webp'  => $client->getAsync('/image/webp')
];

// Wait on all of the requests to complete. Throws a ConnectException
// if any of the requests fail
$results = Promise\unwrap($promises);

// Wait for the requests to complete, even if some of them fail
$results = Promise\settle($promises)->wait();

// You can access each result using the key provided to the unwrap
// function.
echo $results['image']->getHeader('Content-Length');
echo $results['png']->getHeader('Content-Length');

在此示例中,所有4个请求并行执行。注意:只有IO是异步而不是处理结果。但那可能就是你想要的。