pixaye / commando
dev-master
2020-01-10 13:07 UTC
Requires
- php: ^7.1
Requires (Dev)
This package is auto-updated.
Last update: 2024-09-10 23:39:42 UTC
README
Commando 是命令模式的简单实现。它可以使您的应用程序更加灵活和可扩展。
内容
需求
目前唯一的需求是 PHP 7.1+
安装
最简单的安装方式是通过 composer 安装
composer require pixaye/commando
用法
首先,您应该初始化并存储 CommandBus 对象
<?php $bus = new \Commando\Bus\StandardCommandBus([ Commands\SomeCommand::class => new Handlers\SomeCommandHandler(), Commands\SomeAnotherCommand::class => new Handlers\SomeAnotherCommandHandler() ]);
然后,要分发命令,您应该创建命令对象并调用总线上的 dispatch 方法
<?php $bus = new \Commando\Bus\StandardCommandBus([ Commands\RegisterNewUserCommand::class => new Handlers\RegisterNewUserCommandHandler(), ]); //For example, we want to register new user $registeredUser = $bus->dispatch(new Commands\RegisterNewUserCommand('John Doe', '1234567890'));
命令是一个简单的 PHP 类,其中可以包含一些处理器应该使用的属性来执行某些操作。
<?php namespace YourProject\Commands; use Commando\Command\CommandInterface; class RegisterNewUserCommand implements CommandInterface { private $fullName; private $password; /** * @return mixed */ public function getFullName() { return $this->fullName; } /** * @param mixed $fullName */ public function setFullName($fullName) { $this->fullName = $fullName; } /** * @return mixed */ public function getPassword() { return $this->password; } /** * @param mixed $password */ public function setPassword($password) { $this->password = $password; } }
它将调用 RegisterNewUserCommandHandler 的 handle 方法并返回它
重要! - 所有处理器应该实现 Commando\Handler\HandlerInterface,每个命令都应该实现 Commando\Command\CommandInterface
<?php namespace YourProject\Handlers; use Commando\Handler\HandlerInterface; class RegisterNewUserCommandHandler implements HandlerInterface { /** * @param RegisterNewUserCommand $command * @return string */ public function handle($command) { return 'User with name ' . $command->getFullName() . ' and password = ' . $command->getPassword() . ' has been created'; } }