2

I am using guzzle to send some requests:

$response = $this->client->request(new SomeObject());

using the class below

...
public function request(Request $request)
{
    return $this->requestAsync($request)->wait();
}

// Here I'm using Guzzle Async, but I can remove that is needed
public function requestAsync(Request $request)
{
    $promise = $this->http->requestAsync($request->getMethod(), $request->getUri());

    $promise = $promise->then(
        function (ResponseInterface $response) use ($request) {
            return $response;
        }
    );

    return $promise;
}
...

I would like to use ReactPHP to send multiple requests at once in a foreach loop:

$requests = [];
foreach ($data as $value) {
    $requests[] = $this->client->request(new SomeObject());
}

// pass $requests to ReactPHP here and wait on the response

Any ideas?

Patrioticcow
  • 26,422
  • 75
  • 217
  • 337

1 Answers1

2

First of all, you don't need ReactPHP to use parallel HTTP requests with Guzzle. Guzzle itself provides this feature (if you use cURL handler, which is the default).

For example:

$promises = [];
foreach ($data as $value) {
    $promises[] = $guzzleClient->getAsync(/* some URL */);
}

// Combine all promises
$combinedPromise = \GuzzleHttp\Promise\all($promises)

// And wait for them to finish (all requests are executed in parallel)
$responses = $combinedPromise->wait();

If you still want to use Guzzle with ReactPHP event loop, then, unfortunately, there are no straightforward solution. You cat take a look at https://github.com/productsupcom/guzzle-react-bridge (I'm the developer, so feel free to ask questions).

Alexey Shokov
  • 4,775
  • 1
  • 21
  • 22
  • Yeah, I am using Guzzle Async now. It's working great. I just wanted to try ReactPHP and see if I gain any speed. Do you have an example using `guzzle-react-bridge` with something similar to my scenario? – Patrioticcow Sep 20 '18 at 03:42
  • I will search for an example, but it would not lead to speed gain, unfortunately. The `guzzle-react-bridge` provides interoperability, but doesn't replace Guzzle's cURL handler with the ReactPHP. – Alexey Shokov Sep 20 '18 at 10:42