Skip to content

Instantly share code, notes, and snippets.

@mrsimonbennett
Forked from RobinMalfait/Account.php
Last active August 29, 2015 14:22
Show Gist options
  • Save mrsimonbennett/5e152802783c1872e5c2 to your computer and use it in GitHub Desktop.
Save mrsimonbennett/5e152802783c1872e5c2 to your computer and use it in GitHub Desktop.
<?php namespace KBC\Accounts;
use KBC\Accounts\Events\AccountWasDeleted;
use KBC\Accounts\Events\AccountWasOpened;
use KBC\Accounts\Events\MoneyWasWithdrawn;
use KBC\Accounts\Events\MoneyWasDeposited;
use KBC\Core\BaseModel;
final class Account extends BaseModel
{
private $name;
private $balance;
private $id;
private $closed;
public static function open($id, Name $name)
{
$me = new static();
$me->apply(new AccountWasOpened($id, $name, 0));
}
public function delete()
{
$this->apply(new AccountWasDeleted($this->id));
}
public function deposit($amount)
{
if(!$this->closed)
throw new AccountClosed();
$this->apply(new MoneyWasDeposited($this->id, $amount));
}
public function withdraw($amount)
{
if(!$this->closed)
throw new AccountClosed();
$this->apply(new MoneyWasWithdrawn($this->id, $amount));
}
/* Respond to events */
public function applyAccountWasOpened(AccountWasOpened $event)
{
$state->id = $event->id;
$state->balance = $event->balance;
$state->name = $event->name;
}
public function applyMoneyWasDeposited(MoneyWasDeposited $event)
{
$this->balance += $event->amount;
}
public function applyMoneyWasWithdrawn(MoneyWasWithdrawn $event)
{
$state->balance -= $event->amount;
}
public function applyAccountWasDeleted(AccountWasDeleted $event)
{
$this->closed = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment