Bus Mode (CQRS)
Bus Mode implements CQRS (Command Query Responsibility Segregation) where write operations (Commands) and read operations (Queries) are dispatched through dedicated buses. This mode provides middleware support, automatic event dispatching, and transaction management.
Commands and Queries
Commands represent intentions to change state. They are immutable readonly objects named with imperative verbs (CreateBookCommand, UpdateBookCommand). Handlers return void and trigger side effects.
Queries represent requests for data. They are immutable readonly objects named with nouns (ListBooksQuery, DetailBookQuery). They return QueryResponse objects and have no side effects.
Flow Example
From the demo application:
// Controller dispatches command
$command = new CreateBookCommand($id, $title, $author, $isbn);
$this->commandBus->dispatch($command);
// Handler executes business logic
$book = new Book(/* ... */);
$this->bookRepository->save($book);
$this->eventBus->dispatch(new BookCreatedEvent($book));
Benefits
Bus Mode provides several advantages:
- Automatic Event Dispatching: SyncCommandBus publishes domain events after successful execution
- Transaction Management: TransactionalCommandBus wraps execution in database transactions
- Middleware Support: Buses support middleware for logging, validation, authorization
- Async Capability: Architecture supports queuing commands for async processing
When to Use
Bus Mode is recommended when:
- Complex business logic is required
- Domain events are needed
- Multi-entity transactions occur
- Middleware is required (logging, authorization)
- Future async processing is planned
In the demo application, Library, Loan, and User modules use Bus Mode.
See Also
- CQRS - Conceptual foundation for Bus Mode
- Commands & Handlers - Write operation implementation
- Command Bus - Command dispatching plugin
- Transaction - TransactionalCommandBus decorator
- Event Bus - Automatic event dispatching
- Library Module - Bus Mode in practice