Command Query Responsibility Segregation is a simple concept. When you want something to happen, you will use a Command. If you need results returned, you will use a query.
An over simplified example of this would be if you need to write to a database, you would use a Command. If you need results from a database, you would use a Query.
!!! success "Symfony CQRS Bridge" Once the CQRS Symfony Bridge is installed, you can use the Command Bus that comes with that to gain access to additional features and functionality.
!!! success "Symfony CQRS Bridge" Once the CQRS Symfony Bridge is installed, you can use the Query Bus that comes with that to gain addition features and functionality.
Messages
Both Commands and Queries are considered to be messages. It is HIGHLY recommended to use the AbstractMessage class for both Commands and Queries. For all examples I will assume you have extended this class.
!!! note AbstractMessage treats the message as a value object. So using with will return a new instance of the class.
Additional AbstractMessage API
<?phpuseSonsOfPHP\Component\Cqrs\AbstractMessage;classMessageextendsAbstractMessage {}// Create a new instance with multiple paramters$message = (newMessage())->with(['key'=>'value','another'=>'value',// ...]);// Getting all the paramters of the message$parameters = $message->get();// Get a single paramter value// WARNING: If the parameter is not found, an exception will be thrown$userId = $message->get('user.id');
Message Handlers
Both Command and Query Handers are assumed to just be message handlers.
Command Handlers
<?phpuseSonsOfPHP\Contract\Cqrs\Command\CommandBusInterface;classCreateUserHandler{// First argument will be the Command (ie Message)// Second argument is the command buspublicfunction__invoke(CreateUser $command,CommandBusInterface $bus):void {// ... }}
Query Handlers
<?phpuseSonsOfPHP\Contract\Cqrs\Query\QueryBusInterface;classGetUserHandler{// First argument will be the Query (ie Message)// Second argument is the query buspublicfunction__invoke(GetUser $query,QueryBusInterface $bus):?UserInterface {// ... }}
Symfony Bridge
The Symfony Bridge uses Symfony Components to add additional functionality to the CQRS component.