Last active
February 22, 2017 11:22
-
-
Save chalasr/55b80ef23cd9df2627d53d2ed8bdb39c to your computer and use it in GitHub Desktop.
CommandBus simple example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Adhesion | |
{ | |
private $firstname; | |
private $createdAt; | |
public function __construct(string $firstname, string $lastname) | |
{ | |
$this->firstname = $firstname; | |
$this->lastname = $lastname; | |
$this->createdAt = new \DateTime(); | |
} | |
public function getFirstname(): string | |
{ | |
return $this->firstname; | |
} | |
public function getLastname(): string | |
{ | |
return $this->lastname; | |
} | |
public function grtCreatedAt(): \DateTime | |
{ | |
return $this->createAt; | |
} | |
} | |
class CreateAdhesionCommand | |
{ | |
public $firstname; | |
public $lastname; | |
} | |
class CreateAdhesionCommandHandler | |
{ | |
public function handle(CreateAdhesionCommand $command): Adhesion | |
{ | |
$firstname = $command->firstname; | |
$lastname = $command->lastname; | |
if (!is_string($firstname) || !is_string($lastname)) { | |
throw new \InvalidArgumentException('Firstname and lastname must not be null'); | |
} | |
return new Adhesion($firstname, $lastname); | |
} | |
} | |
class CommandBus | |
{ | |
private $commandHandlerMap; | |
public function __construct(array $commandHandlerMap) | |
{ | |
$this->commandHandlerMap = $commandHandlerMap; | |
} | |
public function handle($command) | |
{ | |
$commandClass = get_class($command); | |
if (!isset($this->commandHandlerMap[$commandClass])) { | |
throw new \InvalidArgumentException('There is no handler defined for command '.$commandClass); | |
} | |
return $this->commandHandlerMap[$commandClass]->handle($command); | |
} | |
} | |
$bus = new CommandBus([CreateAdhesionCommand::class => new CreateAdhesionCommandHandler()]); | |
$command = new CreateAdhesionCommand(); | |
$command->firstname = 'Robin'; | |
$command->lastname = 'Chalas'; | |
$adhesion = $bus->handle($command); | |
var_dump($adhesion); | |
dump($adhesion); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Quelques ressources: