2

I am trying to use Guzzle pool in Symfony 2 application. I am thinking to use it because its capability of sending concurrent request at once.

However, since its async in nature I am not sure how can I use it as service in Symfony 2. Since return are not always immediate.

For example lets say I have service called Foo in Symfony which have method like this some what.

function test() 
{ 
    $request = $client->createRequest('GET', 'http://lt/?n=0', ['future' => true]);

    $client->send($request)->then(function ($response) {

        return "\n".$response->getBody();
    });

}

Now I invoke this service like this.

$service = $this->get('foo');
$result = $service->test();
echo $result;// does not work :( echoes out null

Is there any way to get around this problem. I really want to use Future since I need async feature.

nicholasnet
  • 2,117
  • 2
  • 24
  • 46
  • Does `$response` has a `getBody()` method? Have you tried to `var_dump()` your `$response`? – chapay Jan 30 '15 at 06:59
  • Yes I tried that but that would not do any good. Since response is not ready by then. – nicholasnet Jan 30 '15 at 11:56
  • I meant to `var_dump()` it just before `return "\n".$response->getBody();` – chapay Jan 30 '15 at 11:59
  • Response is fine that's not the problem issue is how to deal with React Promise in Symfony which I think what Guzzle uses under the hood. – nicholasnet Jan 30 '15 at 12:02
  • possible duplicate of [Guzzle pool in PHP application](http://stackoverflow.com/questions/28238621/guzzle-pool-in-php-application) –  Feb 11 '15 at 19:43

1 Answers1

0

You have to deal with promises (futures) in your application or wait for results.

About your example: firstly, you don't return anything from test() ;) Because of that you don't get any $result. As I said before, you have to choose between two different ways here: 1) wait for HTTP call inside test() method and return the result itself, or 2) return Promise immediately and deal with it in your app (through then(), otherwise() and wait() in the end).

If you choose async way for the whole app, the code might look like this:

function test() 
{ 
    return $client->getAsync('http://lt/?n=0')
        ->then(function ($response) {
            return "\n".$response->getBody();
        });
}

And later:

$service = $this->get('foo');
$promise = $service->test()->then(function ($responseString) {
    echo $responseString;
});

$promise->wait(); // Here you get the output.

I slightly changed you code for Guzzle 6 (current version of Guzzle that should use in new projects).

BTW, Guzzle uses its own implementation of promises, that isn't connected with React.

Alexey Shokov
  • 4,775
  • 1
  • 21
  • 22