Event Loops with ReactPHP
Run non-blocking I/O with the ReactPHP event loop.
Event Loops with ReactPHP is a free PHP Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
ReactPHP in One Sentence
ReactPHP is a pure-PHP, dependency-free toolkit for non-blocking I/O built around a single event loop. No extension required — it works on stock PHP using stream_select (or ext-event/ext-ev when available). With it you write long-running servers, parallel HTTP clients, and streaming pipelines in plain PHP.
The Global Loop
Modern ReactPHP (v1.2+) exposes a default loop via the static React\EventLoop\Loop facade — no need to pass a loop instance everywhere. Schedule a callback with a timer; the loop runs until it has no more work.
<?php
require 'vendor/autoload.php';
use React\EventLoop\Loop;
Loop::addTimer(1.0, function () {
echo "fired after 1 second\n";
});
echo "scheduled\n";
// Loop::run() is auto-invoked at script shutdown in v1.2+Timers and Periodic Work
Non-blocking timing replaces sleep(). addTimer fires once; addPeriodicTimer repeats. Cancel either to stop. Because these are loop-driven, other tasks keep running while a timer waits.
<?php
use React\EventLoop\Loop;
$count = 0;
$timer = Loop::addPeriodicTimer(0.5, function () use (&$count, &$timer) {
echo 'tick ' . (++$count) . "\n";
if ($count === 4) {
Loop::cancelTimer($timer); // stop after 4 ticks
}
});Promises for Async Results
ReactPHP returns a promise for any operation that completes later. Attach then() for success and a second callback for failure. Promises compose, so you can transform and chain results without nesting callbacks deeply.
<?php
use React\Promise\Promise;
function asyncDouble(int $n): Promise {
return new Promise(function ($resolve) use ($n) {
\React\EventLoop\Loop::addTimer(0.1, fn() => $resolve($n * 2));
});
}
asyncDouble(21)
->then(fn($r) => printf("result: %d\n", $r)) // 42
->catch(fn(\Throwable $e) => printf("err: %s\n", $e->getMessage()));Parallel HTTP with the Async Client
The big win: fire many HTTP requests concurrently from one thread. React\Http\Browser returns promises; React\Promise\all() waits for the whole batch. Ten 1-second requests finish in ~1 second, not 10.
<?php
use React\Http\Browser;
use function React\Promise\all;
$browser = new Browser();
$urls = [
'https://httpbin.org/delay/1',
'https://httpbin.org/delay/1',
'https://httpbin.org/delay/1',
];
$requests = array_map(fn($u) => $browser->get($u), $urls);
all($requests)->then(function (array $responses) {
echo 'all done: ' . count($responses) . " responses\n";
});Fibers Make It Read Synchronously
Callback chains get unwieldy. ReactPHP integrates with react/async, which uses PHP 8.1 Fibers so you can await() a promise and write straight-line code. The coroutine()/async() wrapper runs your function inside a fiber.
<?php
use function React\Async\async;
use function React\Async\await;
use React\Http\Browser;
$main = async(function () {
$browser = new Browser();
$a = await($browser->get('https://httpbin.org/uuid'));
$b = await($browser->get('https://httpbin.org/uuid'));
echo (string) $a->getBody();
echo (string) $b->getBody();
});
$main();A Non-Blocking TCP Server
ReactPHP shines for servers. A SocketServer accepts connections and emits events; each connection is itself a non-blocking stream. One process handles thousands of simultaneous clients.
<?php
use React\Socket\SocketServer;
use React\Socket\ConnectionInterface;
$socket = new SocketServer('127.0.0.1:8080');
$socket->on('connection', function (ConnectionInterface $conn) {
$conn->write("Welcome\n");
$conn->on('data', function ($data) use ($conn) {
$conn->write('echo: ' . $data); // streamed back, non-blocking
});
});
echo "listening on 127.0.0.1:8080\n";An HTTP Server in a Few Lines
The react/http server handles requests with a callback returning a Response (or a promise of one). Because it is a persistent process, you bootstrap dependencies once — but you also own memory management across requests.
<?php
use React\Http\HttpServer;
use React\Http\Message\Response;
use Psr\Http\Message\ServerRequestInterface;
use React\Socket\SocketServer;
$http = new HttpServer(function (ServerRequestInterface $request) {
return Response::json(['path' => $request->getUri()->getPath()]);
});
$http->listen(new SocketServer('0.0.0.0:8000'));
echo "http://0.0.0.0:8000\n";Streaming Without Buffering
ReactPHP streams implement back-pressure: you can pipe() a readable stream into a writable one and the runtime throttles automatically. This lets you move gigabytes through a constant, small memory footprint instead of loading files into RAM.
<?php
use React\Stream\ReadableResourceStream;
use React\Stream\WritableResourceStream;
$source = new ReadableResourceStream(fopen('big.log', 'r'));
$dest = new WritableResourceStream(fopen('php://stdout', 'w'));
$source->pipe($dest); // back-pressure aware, never buffers whole fileThe Cardinal Sin: Blocking the Loop
Everything breaks the moment you call a blocking function inside a handler — sleep(), blocking PDO, curl_exec, file_get_contents on a URL. They freeze the single thread and stall every connection. Use the React equivalents: Loop::addTimer for delays, clue/reactphp-* or async DB drivers for queries, the Browser for HTTP.
<?php
use React\EventLoop\Loop;
use function React\Async\await;
use React\Promise\Deferred;
// BAD: sleep(2); // freezes the entire loop
// GOOD: async delay that yields control
function delay(float $s): \React\Promise\PromiseInterface {
$d = new Deferred();
Loop::addTimer($s, fn() => $d->resolve(null));
return $d->promise();
}
// await(delay(2.0)); // inside a fiber/coroutineLimiting Concurrency
Unbounded fan-out can exhaust file descriptors or hammer a downstream API. ReactPHP's clue/mq-react queues work with a concurrency cap, processing N promises at a time while the rest wait. This back-pressures your own outbound load.
<?php
use Clue\React\Mq\Queue;
use React\Http\Browser;
$browser = new Browser();
// At most 10 in-flight requests across 1000 URLs
$q = new Queue(10, null, fn($url) => $browser->get($url));
$promises = array_map(fn($u) => $q($u), $thousandUrls ?? []);
\React\Promise\all($promises)->then(function ($responses) {
echo 'completed ' . count($responses) . " with cap of 10\n";
});Quick Check
How do you pause for 2 seconds inside a ReactPHP handler without harming concurrency?
Recap
ReactPHP brings non-blocking I/O to vanilla PHP:
- A single event loop (
Loopfacade) drives timers, sockets, and streams — no extension needed. - Operations return promises;
all()runs requests in parallel, andreact/async+ Fibers let youawait()for synchronous-looking code. - Build persistent TCP/HTTP servers and back-pressured streams that handle thousands of connections per process.
- Never block the loop — replace
sleep/blocking I/O with React timers and async drivers.
Frequently asked questions
Is the “Event Loops with ReactPHP” lesson free?
Yes — the full text of “Event Loops with ReactPHP” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.
What will I learn in “Event Loops with ReactPHP”?
Run non-blocking I/O with the ReactPHP event loop. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start PHP Academy?
No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Event Loops with ReactPHP” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this PHP Academy lesson?
Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- The PHP Concurrency Model
- PHP 8.1 Fibers
- Event Loops with ReactPHP
- High-Performance Servers with Swoole