Created
November 10, 2017 12:39
-
-
Save carousel/dc2c61fd34b3c51a47649135e59d926e to your computer and use it in GitHub Desktop.
Guarding aggregate with invariant
This file contains hidden or 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 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