diceline-chartmagnifiermouse-upquestion-marktwitter-whiteTwitter_Logo_Blue

Today I Learned

HTTP pools - Laravel HTTP client

In PHP, unlike JavaScript, we don't have native support for Promises or asynchronous programming. This limitation can become apparent when dealing with multiple HTTP requests that need to be made simultaneously. However, the Http::pool method, as shown in the code snippet, offers a workaround by allowing us to leverage parallel processing.

The code uses the HTTP pools functionality provided by the Laravel HTTP client, which is a convenient way to execute multiple HTTP requests concurrently. Here's an expanded explanation of the code:

//dummy code

$responses = Http::pool(fn (Pool $pool) => [
    $pool->get("https://jsonplaceholder.typicode.com/todos/1"),
    $pool->get("https://jsonplaceholder.typicode.com/users/1"),
    $pool->get("https://jsonplaceholder.typicode.com/posts/1")
]);

$todoInfo = $responses[0]->json();
$userInfo = $responses[1]->json();
$postInfo = $responses[2]->json();

This code snippet demonstrates how to make three (or more) simultaneous HTTP calls to different endpoints using HTTP pools in PHP. In a specific situation on the project I'm working on, this approach significantly reduced the load time from 3 seconds to 1.1 seconds.