Category: PHP

Making concurrent HTTP requests in PHP

This is part of a new series of articles aimed at giving instant responses to common questions. Find out more.


All the snippets make 10 requests to a fake API that takes 3 seconds to reply.

On my computer, multiple executions of these scripts ran in a little more than 3 seconds.

You can configure how many simultaneous connections to make in each client.

Using Symfony’s HTTPClient

Installation

$ composer require symfony/http-client

Example

$client = new \Symfony\Component\HttpClient\CurlHttpClient([], 10);
$responses = [];

for ($i = 0; $i < 10; ++$i) {
    $responses[] = $client->request('GET', 'http://slowwly.robertomurray.co.uk/delay/3000/url/https://jsonplaceholder.typicode.com/todos/1');
}

foreach ($responses as $response) {
    $content = $response->getContent();
}

Using Guzzle

Installation

$ composer require guzzlehttp/guzzle:^7.0

Example

$client = new \GuzzleHttp\Client();
$responses = [];

$generator = function ($total) use ($client) {
    for ($i = 0; $i < $total; $i++) {
        yield function() use ($client) {
            return $client->getAsync('http://slowwly.robertomurray.co.uk/delay/3000/url/https://jsonplaceholder.typicode.com/todos/1');
        };
    }
};

$pool = new \GuzzleHttp\Pool($client, $generator(10), [
    'concurrency' => 10,
    'fulfilled' => function (\GuzzleHttp\Psr7\Response $response, $index) use (&$responses) {
        $responses[$index] = $response->getBody()->getContents();
    },
]);

$promise = $pool->promise();

$promise->wait();

Any comments? Send me a tweet. 🐸

Reading incoming JSON bodies in Symfony

Accepting JSON encoded data from requests is crucial when developing APIs. By default, Symfony will not unserialize the object as an array, and you need a little workaround to make it available as you would with any form submitted request.

We can make use of an EventSubscriber to have the JSON content always decoded and put in $request->request.

(more…)

Debugging scripts with xDebug, Docker and PHPStorm

According to The State of the Developer Ecosystem 2019, 65% of PHP developers relies on var_dump(), dd(), etc… to debug their applications, while only the 35% uses a proper debugger. [1]

Printing the content of a variable is effective, but not really efficient when it comes to follow its lifecycle in an application.

Debugging is an important skill for a developer, but setting up the correct environment may be tedious. I will try to address this in this post.

(more…)