Peter Hahn
Peter Hahn

Reputation: 121

Asynchronous calls in symfony2

How can i call methods asynchronously in symfony2.7 Like.

I have to retrieve data making 4 different API connections. The problem is slow response from my application since PHP is synchronous so it has to wait for the response from all the API and then render the data.

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
  }
}

Upvotes: 0

Views: 2008

Answers (1)

Otto
Otto

Reputation: 450

You can use guzzle for that, especially when we're are talking about http based apis. Guzzle is a web-client which has async calls built in.

The code would look somewhat like this: (taken from the 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');

In this example all 4 requests are executed in parallel. Note: Only IO is async not the handling of the results. But that's probably what you want.

Upvotes: 2

Related Questions