Skip to content

Instantly share code, notes, and snippets.

@devsdmf
Created November 25, 2019 20:05
Show Gist options
  • Save devsdmf/4e006bf6859f8fcf8b66702778bd5b4a to your computer and use it in GitHub Desktop.
Save devsdmf/4e006bf6859f8fcf8b66702778bd5b4a to your computer and use it in GitHub Desktop.
<?php
interface DatabaseDriver {
public function save(string $data);
}
abstract class AbstractPersistence {
private $driver;
public function setDriver(DatabaseDriver $driver) {
$this->driver = $driver;
}
protected function saveEvent(EventInterface $event) {
$this->driver->save($event->serialize());
}
protected function getByReference(array $where) {
$this->driver->findBy($where);
}
}
class Wallet extends AbstractPersistence
{
private $id;
private $value;
public function __construct(int $id) {
$this->id = $id;
$this->value = 0.0;
}
public function handle(WalletEvent $event) {
if ($event->getType() === WalletEvent::EVENT_DEPOSIT) {
$this->addFunds($event->getValue());
} else if ($event->getType() === WalletEvent::EVENT_WITHDRAW) {
$this->removeFunds($event->getValue());
}
}
public function handleAndSave(WalletEvent $event) {
if ($event->getType() === WalletEvent::EVENT_DEPOSIT) {
$this->saveEvent($event);
$this->addFunds($event->getValue());
} else if ($event->getType() === WalletEvent::EVENT_WITHDRAW) {
$this->saveEvent($event);
$this->removeFunds($event->getValue());
}
}
private function addFunds(float $value) {
$this->value += $value;
}
private function removeFunds(float $value) {
$this->value -= $value;
}
public static function fromDatabase($walletId) {
$data = $this->getByReference(['walletId' => $walletId]);
$wallet = new self($walletId);
foreach ($data as $event) {
$wallet->handle($event);
}
return $wallet;
}
}
interface EventInterface extends Serializable{}
interface WalletEvent extends EventInterface {
public const EVENT_DEPOSIT = 'deposit';
public const EVENT_WITHDRAW = 'withdraw';
public function getType(): string;
public function getValue(): float;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment