Note: I recommend using at least the validation middleware on both buses to validate your commands/queries and the doctrine_transaction middleware on the command bus in order to wrap your handler into a transaction that will be rollback in case of exception.
If you prefer, you can create two classes or two interfaces for query and command bus in order to use type-hinting for autowire instead of binding variables.
For example with interfaces:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?phpnamespaceApp\Infra\Bus;useSymfony\Component\Messenger\HandleTrait;useSymfony\Component\Messenger\MessageBusInterface;interfaceCommandBus{publicfunctionhandle($command);}interfaceQueryBus{publicfunctionhandle($query);}classBusimplementsCommandBus,QueryBus{// Same as before ...}
Register query bus and the command bus services and aliases:
<?phpnamespaceApp\Infra\Common\Listener;useApp\Domain\Common\Exception\ForbiddenException;useApp\Domain\Common\Exception\NotFoundException;useSymfony\Component\EventDispatcher\EventSubscriberInterface;useSymfony\Component\HttpKernel\Event\ExceptionEvent;useSymfony\Component\HttpKernel\Exception\AccessDeniedHttpException;useSymfony\Component\HttpKernel\Exception\NotFoundHttpException;useSymfony\Component\HttpKernel\KernelEvents;useSymfony\Component\Messenger\Exception\HandlerFailedException;/** * Converts some of our custom exceptions to HTTP ones to be handled by the framework. */classToHttpExceptionListenerimplementsEventSubscriberInterface{publicfunctiononKernelException(ExceptionEvent$event):void{$ex=$event->getThrowable();// An exception thrown from a Messenger handler is wrapped into a HandlerFailedException:if($exinstanceofHandlerFailedException){$ex=$ex->getPrevious();}switch(true){case$exinstanceofNotFoundException:$event->setThrowable(newNotFoundHttpException($ex->getMessage(),$ex));return;case$exinstanceofForbiddenException:$event->setThrowable(newAccessDeniedHttpException($ex->getMessage(),$ex));return;// Or any other logic for your app}}publicstaticfunctiongetSubscribedEvents(){return[KernelEvents::EXCEPTION=>['onKernelException',10],];}}