The command design pattern is used to encapsulate the parameters of a request. Only scalar types (int, string, etc.) and DTO's are passed to the constructor of this simple data transfer object.
Below we use the ChangePasswordCommand and ChangePasswordHandler to facilitate the call to the UserService changePassword() method. This enables us to later use the Decorator pattern on the CommandBusInterface to add behavior for audit logging, throttling actions, etc.
- Action Design Pattern
- Transaction Design Pattern
final class ChangePasswordCommand implements CommandInterface
{
public function __construct($userId, $password)
{
$this->userId = (int) $userId;
$this->password = (string) $password;
}
}
final class ChangePasswordHandler
{
public function handle(ChangePasswordCommand $command)
{
$this->userService->changePassword(
$command->getUserId(),
$command->getPassword()
);
}
}
$userId = 1;
$newPassword = 'newpassword123';
$this->dispatch(new ChangePasswordCommand($userId, $newPassword));