- Installation
- Introduction
- Commands
- Registering command handlers
- Dispatching commands
- Existing container integrations
composer require weew/commander
Commander is a simple message bus. It allows you to register command handlers and to dispatch commands. The main reason to use such an abstraction is to decouple components and dependencies. The caller never knows who will handle a command after all. All he knows is a set of contracts that both sides have to fulfill.
A command has no restrictions. You can use almost everything as a command. It is recommended to create simple transfer/value objects and use them as commands. A command is basically a contract between the caller and the handler.
To be able to dispatch commands to handlers, commander has to know who is responsible for each command. That is why you have have to register a handler for each command. A handler can be a callable or a class / instance that implements method handle($command)
.
First let's create a very basic command, a handler and a result.
class FooCommandHandler {
public function handle($command) {
return new FooResult();
}
}
class FooCommand {
public function __construct($foo, $bar) {}
}
class FooResult {}
Now comes the command registration.
$commander = new Commander();
$commander->register(FooCommand::class, FooCommandHandler::class);
After you have registered your commands and handlers you can invoke them from anywhere within you application.
$result = $commander->dispatch(new FooCommand('foo', 'bar'));
There is an integration available for the weew/container container. See weew/commander-container-aware.