You can use any implementations of callable type as a command handler.
The command handler can be a anonymous function:
$handler = static function (RenameArticleCommand $command): void {
// do something
};
// register command handler in handler locator
$locator = new DirectBindingCommandHandlerLocator();
$locator->registerHandler(RenameArticleCommand::class, $handler);
It can be a some function:
function RenameArticleHandler(RenameArticleCommand $command): void
{
// do something
}
// register command handler in handler locator
$locator = new DirectBindingCommandHandlerLocator();
$locator->registerHandler(RenameArticleCommand::class, 'RenameArticleHandler');
It can be a called object:
class RenameArticleHandler
{
public function __invoke(RenameArticleCommand $command): void
{
// do something
}
}
// register command handler in handler locator
$locator = new DirectBindingCommandHandlerLocator();
$locator->registerHandler(RenameArticleCommand::class, new RenameArticleHandler());
It can be a static method of class:
class RenameArticleHandler
{
public static function handleRenameArticle(RenameArticleCommand $command): void
{
// do something
}
}
// register command handler in handler locator
$locator = new DirectBindingCommandHandlerLocator();
$locator->registerHandler(RenameArticleCommand::class, 'RenameArticleHandler::handleRenameArticle');
It can be a public method of class:
class RenameArticleHandler
{
public function handleRenameArticle(RenameArticleCommand $command): void
{
// do something
}
}
// register command handler in handler locator
$locator = new DirectBindingCommandHandlerLocator();
$locator->registerHandler(RenameArticleCommand::class, [new RenameArticleHandler(), 'handleRenameArticle']);
You can handle many commands in one handler.
class ArticleHandler
{
public function handleRenameArticle(RenameArticleCommand $command): void
{
// do something
}
public function handlePublishArticle(PublishArticleCommand $command): void
{
// do something
}
}
// register command handler in handler locator
$locator = new DirectBindingCommandHandlerLocator();
$locator->registerHandler(RenameArticleCommand::class, [new ArticleHandler(), 'handleRenameArticle']);
$locator->registerHandler(PublishArticleCommand::class, [new ArticleHandler(), 'handlePublishArticle']);
You can use exists locators of command handler:
Or you can create custom locator that implements GpsLab\Component\Command\Handler\Locator\CommandHandlerLocator
interface.