Asynchronous PHP using ReactPHP

Bhimani Rutvik
Simform Engineering
4 min readMar 22, 2023

Efficiently handle high-traffic PHP applications with ReactPHP’s asynchronous power.

Asynchronous programming provides a solution to traditional synchronous programming problems by allowing tasks to be executed in the background without blocking the main program execution. This means that the program can continue to handle other tasks while the time-consuming tasks are executed in the background.

Benefits of Asynchronous Programming

Asynchronous programming offers several benefits over traditional synchronous programming in PHP. Here are some of the key benefits of using asynchronous programming in PHP:

  1. Improved performance: Asynchronous programming allows tasks to be executed concurrently, which can significantly improve the performance of web applications. By executing time-consuming tasks in the background, the program can continue to handle other requests without waiting for the previous request to complete.
  2. Scalability: Asynchronous programming can improve the scalability of web applications by handling multiple requests concurrently, thereby allowing web applications to handle more requests without compromising the application’s performance.
  3. Better resource utilization: By executing tasks in the background, the program can avoid idle time while waiting to complete long-running tasks and efficiently utilize system resources.
  4. Responsiveness: Asynchronous programming can improve the responsiveness of web applications. By handling multiple requests concurrently, web applications can provide a more interactive and responsive user experience.
  5. Reduced costs: Asynchronous programming can handle more requests with fewer resources and thus reduce the cost of running web applications.
credit: to respective owner

Let’s see ReactPHP in action

Prerequisites

PHP ≥ 8.1

ReactPHP contains a set of individual components that you can plug and play with help of a Composer.

# recommended install: pick required components
composer require react/event-loop react/http react/promise react/async
#Note: Async function available only in react/async version 4.X

Example 1

Write asynchronous code using Loop class with ReactPHP

<?php
require __DIR__ . '/vendor/autoload.php';

Loop::addTimer(0.5, React\Async\async(function () {
echo 'I am going to office';
React\Async\await(React\Promise\Timer\sleep(1.0));
echo 'I am going to home';
}));

Loop::addTimer(1.0, function () {
echo 'I have taken my lunch yummmmmmmmmmm';
});
Fig-1: Output of example-1

Example 2 :

Let's run the code parallelly

<?php

require __DIR__ . '/vendor/autoload.php';

use React\EventLoop\Loop;
use React\Promise\Promise;

React\Async\parallel([
function () {
return new Promise(function ($resolve) {
Loop::addTimer(5, function () use ($resolve) {
$promise = React\Async\coroutine(function () {
$browser = new React\Http\Browser();
$response = yield $browser->get('https://jsonplaceholder.typicode.com/posts');
assert($response instanceof Psr\Http\Message\ResponseInterface);
$bytes = $response->getBody()->getSize();
return $bytes;
});

$promise->then(function (int $bytes) use ($resolve) {
$resolve("Content Downloaded");
});

});
});
},
function () {
return new Promise(function ($resolve) {
Loop::addTimer(1, function () use ($resolve) {
$resolve('I am sleeping for 1 second');
});
});
},
function () {
return new Promise(function ($resolve) {
Loop::addTimer(1, function () use ($resolve) {
$resolve('I am sleeping another whole second');
});
});
},
])->then(function (array $results) {
foreach ($results as $result) {
var_dump($result);
}
}, function (Exception $e) {
echo 'Error: ' . $e->getMessage() . PHP_EOL;
});

The React\Async\parallel() function takes an array of callback functions that return promises. Each callback function represents a task that should be executed in parallel.

For the first task, the callback function creates a new Promise and sets a timer for 5 seconds using Loop::addTimer(). Once the timer expires, it uses the React\Async\coroutine() function to create a coroutine. This coroutine uses the React\Http\Browser() to make an HTTP GET request to the JSON API and returns the size of the response body. Once the promise is resolved, it calls the $resolve() function with the result.

The second and third tasks simply sleep for one second each and then resolve their promises with a string.

Finally, the then() function is called on the result of the parallel() function to handle the resolved promises. It takes two callback functions: one to handle successful resolutions and another to handle rejections. In this case, the successful resolution callback function loops through the array of results and prints each. The back function prints an error message if any promise is rejected.

Fig-2: Output of example-2

Wrapping up

Asynchronous programming with ReactPHP can significantly improve web applications' performance, scalability, and responsiveness while utilizing system resources more efficiently.

With the examples provided, it’s clear that ReactPHP offers a powerful toolkit for building high-performance web applications in PHP. You can explore the capabilities of ReactPHP here.

Stay tuned and follow Simform Engineering for important and exciting updates on various tools and technologies.

--

--

Bhimani Rutvik
Simform Engineering

Web Developer at Simform || Be smarter everyday Talks about #ci, #php, #devloper and #webdevloper