Previous pages provide the background on how to handle command messages in your application. The dispatching process is the starting point for command message.
Command Bus
is special type of Messaging Gateway.
namespace Ecotone\Modelling;​interface CommandBus{// 1public function send(object $command, array $metadata = []) : mixed;​// 2public function sendWithRouting(string $routingKey, mixed $command, string $commandMediaType = MediaType::APPLICATION_X_PHP, array $metadata = []) : mixed;}
Command is routed to the Handler by class type.
// Command Bus will be auto registered in Depedency Container.class TicketController{private CommandBus $commandBus;​public function __construct(CommandBus $commandBus){$this->commandBus = $commandBus;}public function closeTicketAction(Request $request) : Response{$this->commandBus->send(new CloseTicketCommand($request->get("ticketId")));}}
$commandBus = $messagingSystem->getGatewayByName(CommandBus::class);​$commandBus->send(new CloseTicketCommand($ticketId));
class CloseTicketCommandHandler{#[CommandHandler]public function closeTicket(CloseTicketCommand $command){// handle closing ticket}}
Does allow for passing extra meta information
, that can be used on targeted Command Handler
.
class TicketController{private CommandBus $commandBus;​public function __construct(CommandBus $commandBus){$this->commandBus = $commandBus;}public function closeTicketAction(Request $request, Security $security) : Response{$this->commandBus->sendWithMetadata(new CloseTicketCommand($request->get("ticketId")),["executorUsername" => $security->getUser()->getUsername()]);}}
$commandBus = $messagingSystem->getGatewayByName(CommandBus::class);​$commandBus->sendWithMetadata(new CloseTicketCommand($ticketId),["executorUsername" => $executorUsername]);
class CloseTicketCommandHandler{#[CommandHandler]public function closeTicket(CloseTicketCommand $command, array $metadata){$ticket = ; // get Ticket using commandif ($metadata["executorUsername"] !== $ticket->getOwner()) {throw new \InvalidArgumentException("Insufficient permissions")}// handle closing ticket}}
Is used with Command Handlers,
routed by name and converted using Converter if needed.
class TicketController{private CommandBus $commandBus;​public function __construct(CommandBus $commandBus){$this->commandBus = $commandBus;}public function closeTicketAction(Request $request) : Response{$commandBus->convertAndSend("closeTicket", "application/json", '{"ticketId": 123}');}}
$commandBus = $messagingSystem->getGatewayByName(CommandBus::class);​$commandBus->convertAndSend("closeTicket","application/json",'{"ticketId": 123}');
class CloseTicketCommandHandler{#[CommandHandler]public function closeTicket(CloseTicketCommand $command){// handle closing ticket}}