Skip to content

Instantly share code, notes, and snippets.

@chalasr
Last active February 22, 2017 11:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chalasr/55b80ef23cd9df2627d53d2ed8bdb39c to your computer and use it in GitHub Desktop.
Save chalasr/55b80ef23cd9df2627d53d2ed8bdb39c to your computer and use it in GitHub Desktop.
CommandBus simple example
<?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);
@chalasr
Copy link
Author

chalasr commented Feb 22, 2017

Quelques ressources:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment