Simplified CQRS with Symfony Messenger
CQRS (Command Query Responsibility Segregation) splits your application into two sides:
- Commands change state: create a post, publish it, delete it. They don't return data.
- Queries read state: get a post, list posts. They don't change anything.
You don't need event sourcing or separate databases to get value from this. A command bus and a query bus in Symfony Messenger are enough to make the split clear in your code. This post builds that setup for a simple blog.
Two buses
Install Messenger:
composer require symfony/messenger
Define both buses in config/packages/messenger.yaml:
framework:
messenger:
default_bus: command.bus
buses:
command.bus:
middleware:
- validation
- doctrine_transaction
query.bus:
middleware:
- validation
transports:
async: '%env(MESSENGER_TRANSPORT_DSN)%'
That's all the configuration you need. Symfony creates both bus services and registers them for autowiring by name: a MessageBusInterface $commandBus argument gets the command bus, $queryBus gets the query bus.
The middleware is different per bus. Commands run inside a database transaction, so a failing handler doesn't leave half-written data behind. Queries only read, so they don't need one.
The command
A command is a plain object with the data needed to do one thing:
// src/CQRS/Command/CreatePost.php
namespace App\CQRS\Command;
use Symfony\Component\Uid\Uuid;
final readonly class CreatePost
{
public function __construct(
public Uuid $id,
public string $title,
public string $content,
public string $authorId,
) {}
}
The command carries its own ID. The controller generates it, not the database. That sounds like a detail, but it means the command never has to return anything. The caller already knows the ID of the post it asked for. This becomes important once commands run async.
The handler does the actual work:
// src/CQRS/CommandHandler/CreatePostHandler.php
namespace App\CQRS\CommandHandler;
use App\CQRS\Command\CreatePost;
use App\Entity\Post;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
#[AsMessageHandler(bus: 'command.bus')]
final readonly class CreatePostHandler
{
public function __construct(
private EntityManagerInterface $entityManager,
) {}
public function __invoke(CreatePost $command): void
{
$post = new Post(
id: $command->id,
title: $command->title,
content: $command->content,
authorId: $command->authorId,
createdAt: new \DateTimeImmutable(),
);
$this->entityManager->persist($post);
}
}
The bus option is important. Without it, Symfony registers the handler on every bus, and your query bus could suddenly handle commands.
There's no flush() here. The doctrine_transaction middleware flushes and commits after the handler is done.
The query
Queries look the same, but they return data:
// src/CQRS/Query/GetPost.php
namespace App\CQRS\Query;
use Symfony\Component\Uid\Uuid;
final readonly class GetPost
{
public function __construct(
public Uuid $id,
) {}
}
The handler returns a read model, not the Doctrine entity:
// src/CQRS/QueryHandler/GetPostHandler.php
namespace App\CQRS\QueryHandler;
use App\CQRS\Query\GetPost;
use App\CQRS\ReadModel\PostView;
use App\Repository\PostRepository;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
#[AsMessageHandler(bus: 'query.bus')]
final readonly class GetPostHandler
{
public function __construct(
private PostRepository $posts,
) {}
public function __invoke(GetPost $query): ?PostView
{
$post = $this->posts->find($query->id);
if ($post === null) {
return null;
}
return new PostView(
id: (string) $post->getId(),
title: $post->getTitle(),
content: $post->getContent(),
);
}
}
// src/CQRS/ReadModel/PostView.php
namespace App\CQRS\ReadModel;
final readonly class PostView
{
public function __construct(
public string $id,
public string $title,
public string $content,
) {}
}
PostView contains exactly what the client needs. You can serialize it to JSON without worrying about lazy-loaded relations or fields that should stay private.
Getting query results back
Messenger's dispatch() returns an envelope, not the handler's return value. You could dig the result out of the HandledStamp every time, but HandleTrait does that for you. Wrap it in a small class:
// src/CQRS/QueryBus.php
namespace App\CQRS;
use Symfony\Component\Messenger\HandleTrait;
use Symfony\Component\Messenger\MessageBusInterface;
final class QueryBus
{
use HandleTrait;
public function __construct(MessageBusInterface $queryBus)
{
$this->messageBus = $queryBus;
}
public function ask(object $query): mixed
{
return $this->handle($query);
}
}
handle() also throws an exception if no handler or more than one handler picked up the query, so mistakes in your wiring show up right away.
The controller
// src/Controller/PostController.php
namespace App\Controller;
use App\CQRS\Command\CreatePost;
use App\CQRS\Query\GetPost;
use App\CQRS\QueryBus;
use App\Dto\CreatePostRequest;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Uid\Uuid;
final class PostController extends AbstractController
{
public function __construct(
private readonly MessageBusInterface $commandBus,
private readonly QueryBus $queryBus,
) {}
#[Route('/posts', name: 'post_create', methods: ['POST'])]
public function create(#[MapRequestPayload] CreatePostRequest $request): JsonResponse
{
$id = Uuid::v7();
$this->commandBus->dispatch(new CreatePost(
id: $id,
title: $request->title,
content: $request->content,
authorId: $this->getUser()->getUserIdentifier(),
));
return $this->json(['id' => (string) $id], Response::HTTP_ACCEPTED);
}
#[Route('/posts/{id}', name: 'post_show', methods: ['GET'])]
public function show(Uuid $id): JsonResponse
{
$post = $this->queryBus->ask(new GetPost($id));
if ($post === null) {
throw $this->createNotFoundException();
}
return $this->json($post);
}
}
#[MapRequestPayload] turns the JSON body into a CreatePostRequest DTO and validates it:
// src/Dto/CreatePostRequest.php
namespace App\Dto;
use Symfony\Component\Validator\Constraints as Assert;
final readonly class CreatePostRequest
{
public function __construct(
#[Assert\NotBlank, Assert\Length(max: 200)]
public string $title,
#[Assert\NotBlank]
public string $content,
) {}
}
Invalid input gets a 422 response before your controller code runs. The $commandBus argument name is enough for Symfony to inject the right bus.
Running commands async
Creating a post is fast, but some commands aren't: sending emails, resizing images, calling a slow API. Those can run in the background. Mark the command with #[AsMessage]:
use Symfony\Component\Messenger\Attribute\AsMessage;
#[AsMessage('async')]
final readonly class CreatePost
{
// ...
}
Set the transport in .env:
MESSENGER_TRANSPORT_DSN=doctrine://default
And start a worker:
php bin/console messenger:consume async
Now dispatch() puts the command on the queue and the controller returns right away. The handler runs later, in the worker.
This is where the generated ID pays off. An async command has no result to return, because the handler hasn't run yet when the controller responds. The controller already has the ID, so it can return it anyway. The client uses that ID to fetch the post once the worker is done. That's also why the controller responds with 202 Accepted instead of 201 Created.
Don't make queries async. A query exists to return data right now.
Multiple read models
The read side doesn't have to mirror your entities. Different screens need different data, so give each its own query and read model:
GetPostreturns aPostViewwith the full content.ListPostsreturns a list ofPostSummaryobjects with only title and date.SearchPostscould read from a search index instead of the database.
Adding a read model doesn't touch a single command or command handler.
Start with one part of your application where reads and writes are getting tangled. You don't have to move everything to commands and queries at once.