Skip to content

Instantly share code, notes, and snippets.

@carousel
Created November 10, 2017 12:39
Show Gist options
  • Save carousel/dc2c61fd34b3c51a47649135e59d926e to your computer and use it in GitHub Desktop.
Save carousel/dc2c61fd34b3c51a47649135e59d926e to your computer and use it in GitHub Desktop.
Guarding aggregate with invariant
<?php
class Order
{
protected $basket = [];
protected $maxSize;
protected $confirmed = false;
private function __construct($product)
{
$this->product = $product;
$this->maxSize = 10;
}
public static function instance($product)
{
return new static($product);
}
public function add($product)
{
if (count($this->basket) >= $this->maxSize) {
throw new \Exception('Invariant broken!!!');
}
$this->products[] = $product;
}
public function confirm()
{
if ($this->confirmed == true) {
throw new \Exception('Order is already confirmed!!!');
}
$this->confirmed = true;
}
}
$order = Order::instance(10);
for ($i= 0; $i < 2; $i++) {
$order->add(10);
}
$order->confirm();
$order->confirm();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment