People’s Postcode Lottery - PHP Workshop - March 2017
Behavioural Design Pattern
Encapsulate the behaviour of an action
Encapsulation of a Request
as an Object
Abstraction to an underlying
Domain Concept
class AddToBasketCommand
{
private $basketId;
private $item;
public function __construct($basketId, $item)
{
$this->basketId = $basketId;
$this->item = $item;
}
public function getBasketId()
{
return $this->basketId;
}
public function getItem()
{
return $this->item;
}
}
Commands are just data structures, no behaviour themselves
1 Command = 1 Handler
Handlers Manage Domain Logic
No More Object Saves In Controllers!
Don't do secondary actions in Handlers
class AddToBasketCommandHandler
{
private $repository;
public function __construct($basketRepository)
{
$this->repository = $basketRepository;
}
public function execute(AddToBasketCommand $command)
{
$basket = $this->repository->find(
$command->getBasketId()
);
$basket->addItem($command->getItem());
$basket->save();
}
}
Unit tests for handlers
Unit test handler collaborators
Integration test against Message Bus (sometimes...)
Separation of Read/Write data
Queries defined as objects as well
Further separation of concerns
All actions produce Domain Events
State is replayable at any time
Explicit audit log
No data loss
https://php-and-symfony.matthiasnoback.nl/2015/01/from-commands-to-events/
http://verraes.net/2015/02/form-command-model-validation/
http://www.blackwasp.co.uk/Command.aspx