Separate commands and queries: Use CQRS to decouple write operations (such as CreateUser) from read operations (such as GetUserById), the command side processes business logic and saves events, and the query side quickly obtains data from optimized read tables (such as users_view); 2. Implement event traceability: Record and playback events (such as UserCreated) through the aggregate root (Aggregate Root), state changes are persisted in the form of events, supporting audit, debugging and state reconstruction; 3. Build event storage: Use MySQL and other databases to store event streams, load event sequences according to the aggregate ID to reconstruct aggregate instances; 4. Update the read model: apply events synchronously or asynchronously to the read model table through the projector to keep the query view updated; 5. Gradually iterated: no framework is required, start with a simple implementation, focus on event serialization, version control and aggregation testing, and ensure that the logic of the core field is reliable. After correct implementation, the system will have high scalability, traceability and flexible evolution capabilities.
Building a CQRS and Event Sourcing system in PHP might sound intimidating at first, but once you break it down, it becomes a powerful way to design scalable and maintainable applications—especially when dealing with complex business logic. Here's a practical guide to help you get started, without drowning in theory.

What You're Actually Building
CQRS (Command Query Responsibility Segregation) means separating write operations (commands) from read operations (queries).
Event Sourcing means storing state changes as a sequence of events, rather than just the current state.
Together, they allow you to:

- Track why and how data changed (audit trail by design)
- Rebuild state from events (great for debugging or analytics)
- Scale reads and writes independently
Let's walk through a simplified but real-world-like implementation in PHP.
1. Structure Your Application with CQRS Boundaries
Start by splitting your app into two sides:

- Command Side : Handles actions like "CreateUser", "UpdateEmail"
- Query Side : Handles data fetching like "GetUserById", "ListUsers"
// Example: Command class CreateUserCommand { public function __construct( public readonly string $userId, public readonly string $name, public readonly string $email ) {} } // Example: Command Handler class CreateUserHandler { private EventStore $eventStore; public function __construct(EventStore $eventStore) { $this->eventStore = $eventStore; } public function __invoke(CreateUserCommand $command): void { $user = User::fromCommand($command); $this->eventStore->save($user->getUncommittedEvents()); $user->clearEvents(); // Important: reset after saving } }
On the query side, keep it simple and fast:
class UserQueryHandler { private PDO $pdo; public function getUserById(string $id): ?array { $stmt = $this->pdo->prepare("SELECT * FROM users_view WHERE id = ?"); $stmt->execute([$id]); return $stmt->fetch(PDO::FETCH_ASSOC) ?: null; } }
? Key idea: The query side reads from a denormalized table (like
users_view
) optimized for reads. The command side updates the event store.
2. Implement Event Sourcing with an Aggregate Root
An aggregate is a cluster of domain objects treated as a single unit. For example, User
is an aggregate root.
abstract class AggregateRoot { protected array $events = []; protected int $version = 0; protected function recordEvent(DomainEvent $event): void { $this->events[] = $event; $this->apply($event); } abstract protected function apply(DomainEvent $event): void; public function getUncommittedEvents(): array { return $this->events; } public function clearEvents(): void { $this->events = []; } public function getVersion(): int { return $this->version; } }
Now, build a User
aggregate:
class User extends AggregateRoot { private string $id; private string $name; private string $email; private bool $active = true; public static function create(CreateUserCommand $command): self { $user = new self(); $user->recordEvent(new UserCreated( $command->userId, $command->name, $command->email )); return $user; } protected function apply(DomainEvent $event): void { switch ($event) { case $event instance of UserCreated: $this->id = $event->userId; $this->name = $event->name; $this->email = $event->email; $this->version ; break; } } }
And the event:
class UserCreated implements DomainEvent { public function __construct( public readonly string $userId, public readonly string $name, public readonly string $email, public readonly DateTimeImmutable $occurredAt = new DateTimeImmutable() ) {} }
3. Build a Simple Event Store
The event store saves events and loads them to rebuild aggregates.
interface EventStore { public function save(string $aggregateType, string $aggregateId, array $events, int $expectedVersion): void; public function load(string $aggregateId): array; } class MySqlEventStore implements EventStore { private PDO $pdo; public function __construct(PDO $pdo) { $this->pdo = $pdo; } public function save(string $aggregateType, string $aggregateId, array $events, int $expectedVersion): void { $this->pdo->beginTransaction(); foreach ($events as $event) { $stmt = $this->pdo->prepare( "INSERT INTO events (aggregate_type, aggregate_id, type, payload, version, occurred_at) VALUES (?, ?, ?, ?, ?, ?, ?)" ); $stmt->execute([ $aggregateType, $aggregateId, get_class($event), json_encode($event), $this->version , // Increment per event $event->occurredAt->format('Ymd H:i:s.u') ]); } $this->pdo->commit(); } public function load(string $aggregateId): array { $stmt = $this->pdo->prepare("SELECT * FROM events WHERE aggregate_id = ? ORDER BY version"); $stmt->execute([$aggregateId]); $events = []; foreach ($stmt as $row) { $payload = json_decode($row['payload'], true); // In real apps, use a mapper or serializer $events[] = match ($row['type']) { UserCreated::class => new UserCreated( $payload['userId'], $payload['name'], $payload['email'], new DateTimeImmutable($payload['occurredAt']) ), default => throw new \Exception("Unknown event: " . $row['type']) }; } return $events; } }
? Tip: You'll want to version your events and handle schema changes later (eg, using upcasters).
4. Rebuild State from Events
When loading a User
, replay all events:
class User extends AggregateRoot { // ... previous code public static function fromHistory(array $events): self { $user = new self(); foreach ($events as $event) { $user->apply($event); $user->version ; } return $user; } }
Usage in handler:
public function __invoke(CreateUserCommand $command): void { $events = $this->eventStore->load($command->userId); if (!empty($events)) { throw new \Exception("User already exists"); } $user = User::create($command); $this->eventStore->save('User', $command->userId, $user->getUncommittedEvents(), $user->getVersion()); $user->clearEvents(); }
5. Update the Read Model (Projections)
After an event is saved, update your read-optimized tables.
interface Projector { public function project(DomainEvent $event): void; } class UserProjector implements Projector { private PDO $pdo; public function project(DomainEvent $event): void { if ($event instanceof UserCreated) { $this->pdo->prepare( "INSERT INTO users_view (id, name, email, created_at) VALUES (?, ?, ?, ?)" )->execute([ $event->userId, $event->name, $event->email, $event->occurredAt->format('Ymd H:i:s') ]); } } }
You can run projects:
- Synchronously (simple, consistent)
- Via a message queue (scalable, eventual consistency)
Final Notes
- Use dependency injection (eg, Symfony, Laravel, or plain container)
- Serialize events carefully—prefer JSON or MessagePack over PHP serialization
- Consider using UUIDs for aggregate IDs
- Add metadata to events (eg, user IP, trace ID)
- Test your aggregates heavily—they're the core of your domain
It's not trivial, but you don't need a framework to get started. With plain PHP, interfaces, and good separation, you can build a solid foundation. The real power shows up when your business rules grow and you need to audit, replay, or extend behavior without breaking things.
Basically: start small, get the flow right, and let the events do the talking.
The above is the detailed content of Building a CQRS and Event Sourcing System with PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech
