DEV Community

Cover image for Make a simple Command Bus in PHP
Valeriu Guțu
Valeriu Guțu

Posted on

Make a simple Command Bus in PHP

What is a Command Bus?

A command bus is a design pattern used to manage and execute commands in a PHP application. It acts as a central dispatch mechanism for sending and handling commands, making it easier to manage the flow of requests in a system.

In a command bus architecture, commands are objects that represent a specific request or action that needs to be performed. The command bus is responsible for receiving these commands and forwarding them to the appropriate handler for execution. The handler is a class that implements the logic for a specific type of command, and it returns the result of the command execution to the bus.

Here's a simple example of a command bus in PHP:

<?php
interface CommandBus {
    public function handle(Command $command);
}

class SimpleCommandBus implements CommandBus {
    private $handlers = [];

    public function registerHandler(string $commandName, callable $handler) {
        $this->handlers[$commandName] = $handler;
    }

    public function handle(Command $command) {
        $handler = $this->handlers[get_class($command)];
        $handler($command);
    }
}

class DepositCommand {
    private $amount;

    public function __construct(float $amount) {
        $this->amount = $amount;
    }

    public function getAmount(): float {
        return $this->amount;
    }
}

class DepositCommandHandler {
    public function handle(DepositCommand $command) {
        // Deposit the funds
    }
}

$commandBus = new SimpleCommandBus();
$commandBus->registerHandler(DepositCommand::class, [new DepositCommandHandler(), 'handle']);

$commandBus->handle(new DepositCommand(100.0));
php?>
Enter fullscreen mode Exit fullscreen mode

In this example, the SimpleCommandBus implements the CommandBus interface and acts as the central dispatch mechanism for commands. The DepositCommand represents a request to deposit funds, and the DepositCommandHandler implements the logic for handling the deposit request. The external code sends the command to the command bus, which forwards it to the appropriate handler for execution.

Conclusion

The command bus provides a clear and organized way to manage the flow of requests in the system, making it easier to maintain and extend.

Top comments (0)