Event-driven Architecture in PHP: Writing Asynchronous Code Without Pain

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

When Your PHP Code Stops Being Just a Script

\n\n

Have you ever run a PHP script that processed a thousand emails and waited a minute for it to complete? Or tried to make a chat in plain PHP and realized that without constantly refreshing the page it's impossible? If so — you've already encountered the limitations of the traditional synchronous approach.

\n\n

Event-driven architecture in PHP is not just a trendy term from the Node.js world. It's a real way to make your code faster, more responsive, and more scalable. In this article, we'll break down how event-driven programming works in PHP, write several live examples, and understand when it's really needed.

\n\n

What is Event-driven Architecture in Simple Terms

\n\n

Imagine an office where every employee works strictly according to instructions: "Do A, then B, then C." This is synchronous code. Now imagine an office where employees react to events: "When an email arrives — reply to it," "When an order is placed — send a notification." This is event-driven architecture.

\n\n

In event-driven architecture in PHP, the program does not execute linearly. Instead, it waits for events (click, request, timer, task completion) and reacts to them. The main component here is the event loop, which constantly checks if something has happened and runs the appropriate handlers.

\n\n

Why PHP Developers Should Pay Attention to This

\n\n

For a long time, PHP was associated exclusively with synchronous execution: a request came in — the script ran — a response was sent. But with the emergence of libraries like ReactPHP and Amp, everything changed. Now you can:

\n\n
    \n
  • Handle thousands of WebSocket connections simultaneously
  • \n
  • Execute background tasks without queues like RabbitMQ
  • \n
  • Build real microservices in pure PHP
  • \n
  • Write asynchronous HTTP clients and servers
  • \n
\n\n

And all of this — without changing the language or rewriting the entire codebase.

\n\n

Main Components of Event-driven Architecture

\n\n

Before writing code, let's understand the key concepts. In any event-driven system in PHP, there are three main elements:

\n\n
    \n
  • Event loop — an infinite loop that listens for events (timers, sockets, signals) and dispatches them to handlers.
  • \n
  • Emitter/Dispatcher — an object that generates and sends events.
  • \n
  • Listener/Handler — a function or method that reacts to a specific event.
  • \n
\n\n

In classic PHP, you would write: file_get_contents('https://api.example.com') — and wait for the response. In the event-driven approach, you subscribe to the "data received" event and continue executing other code.

\n\n

Example 1: Simple Event Dispatcher in Pure PHP

\n\n

Let's implement a basic event dispatcher without external libraries. This will help understand the essence of event-driven programming in PHP.

\n\n
<?php\n\nclass EventDispatcher {\n    private array $listeners = [];\n\n    public function addListener(string $eventName, callable $listener): void {\n        $this->listeners[$eventName][] = $listener;\n    }\n\n    public function dispatch(string $eventName, mixed $data = null): void {\n        if (!isset($this->listeners[$eventName])) {\n            return;\n        }\n        foreach ($this->listeners[$eventName] as $listener) {\n            call_user_func($listener, $data);\n        }\n    }\n}\n\n// Usage\n$dispatcher = new EventDispatcher();\n\n$dispatcher->addListener('user.registered', function ($userData) {\n    echo "Sending welcome email for {$userData['email']}\\n";\n});\n\n$dispatcher->addListener('user.registered', function ($userData) {\n    echo "Logging user registration {$userDa                

Blogs

Book Recommendations