Skip to Content
Course content

157: ReactPHP for Event-Driven PHP

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I want to show you something that almost everyone trips over when they first move from traditional synchronous PHP to ReactPHP. You've spent years writing PHP where the code executes line-by-line, and the server waits for the database or an API to respond before moving on. In the event-driven world, that habit will absolutely kill your application's performance.

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

$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) {
    // Imagine this is a slow external API call
    $data = file_get_contents('https://api.example.com/slow-endpoint'); 
    
    return React\Http\Message\Response::plaintext("The API said: " . $data);
});

$socket = new React\Socket\SocketServer('0.0.0.0:8080');
$http->listen($socket);

echo "Server running at http://127.0.0.1:8080\n";

The Silent Freeze

At first glance, this looks fine. It's a simple HTTP server that fetches some data and returns it. But here is the problem: if you open two browser tabs and hit that endpoint simultaneously, the second request won't even start until the first one is completely finished. Your "asynchronous" server is behaving exactly like a slow, single-threaded synchronous script.

The culprit is file_get_contents(). This is a blocking function. Because ReactPHP runs on a single-threaded event loop, when you call a blocking function, you aren't just pausing that one request—you are pausing the entire server. The event loop literally stops spinning, and no other events (like new TCP connections) can be processed until that network call returns.

Switching to Non-Blocking I/O

To fix this, we have to stop using PHP's built-in filesystem and network functions and instead use the ReactPHP ecosystem. We need a client that returns a Promise instead of the actual data. This tells the event loop: "Go ahead and handle other requests; just let me know when this specific data arrives."

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

$loop = React\EventLoop\Loop::get();
$browser = new React\Http\Browser(); // This is the non-blocking client

$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) use ($browser) {
    // We return the promise itself, not the response
    return $browser->get('https://api.example.com/slow-endpoint')
        ->then(function (Psr\Http\Message\ResponseInterface $response) {
            return React\Http\Message\Response::plaintext("The API said: " . (string)$response->getBody());
        }, function (Exception $e) {
            return React\Http\Message\Response::plaintext("Error: " . $e->getMessage())->withStatus(500);
        });
});

$socket = new React\Socket\SocketServer('0.0.0.0:8080');
$http->listen($socket);

echo "Server running at http://127.0.0.1:8080\n";

How the Event Loop Actually Handles This

Notice the difference in the logic flow. In the fixed version, $browser->get() initiates the request and immediately returns a Promise object. It doesn't wait for the bytes to come back from the wire.

  • The server hands that Promise back to the ReactPHP HTTP handler.
  • The event loop is now free to pick up the next incoming request from a different user.
  • When the external API finally responds, the event loop triggers the then() callback.
  • Only then is the final response sent back to the original client.

I can't stress this enough: if you use sleep(), PDO (without a wrapper), or curl_exec() inside a ReactPHP loop, you've effectively turned your high-performance server back into a standard PHP script, but with more overhead. Always look for the "async" version of the library you're using.




📋 Practical Task

Build a Concurrent Website Availability Checker

Your task is to create a CLI tool using ReactPHP that checks the status of multiple websites simultaneously. Instead of checking them one-by-one in a loop (which would be slow), you must initiate all requests concurrently.

Requirements:

  • Create an array of at least 5 different URLs (e.g., google.com, github.com, etc.).
  • Use React\Http\Browser to send a GET request to each URL.
  • Use React\Promise\all() to wait for all requests to complete.
  • When all requests are finished, print a summary list showing which sites returned a 200 OK status and which ones failed.
  • The total execution time of the script should be roughly equal to the slowest single request, not the sum of all requests.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.