interface BalanceInterface
{
public function get();
public function inc($value);
public function dec($value);
}
class Balance implements BalanceInterface
{
private $value;
public function get()
{
return $this->value;
}
public function inc($value)
{
$this->value += $value;
}
public function dec($value)
{
$this->value -= $value;
}
}
class CacheBalance implements BalanceInterface
{
/**
* @var BalanceInterface
*/
private $next;
/**
* @var \Psr\Cache\CacheItemPoolInterface
*/
private $cache;
public function __construct(BalanceInterface $next, \Psr\Cache\CacheItemPoolInterface $cache)
{
$this->next = $next;
$this->cache = $cache;
}
public function get()
{
$item = $this->cache->getItem('balance');
if ($item->isHit()) {
return $item->get();
}
$value = $this->next->get();
$item->set($value);
$this->cache->save($item);
return $value;
}
public function inc($value)
{
return $this->next->inc($value);
}
public function dec($value)
{
return $this->next->dec($value);
}
}
class LogBalance implements BalanceInterface
{
/**
* @var BalanceInterface
*/
private $next;
/**
* @var \Psr\Log\LoggerInterface
*/
private $logger;
public function __construct(BalanceInterface $next, \Psr\Log\LoggerInterface $logger)
{
$this->next = $next;
$this->logger = $logger;
}
public function get()
{
return $this->next->get();
}
public function inc($value)
{
$this->logger->info(sprintf('Increase balance by %d', $value));
return $this->next->inc($value);
}
public function dec($value)
{
$this->logger->info(sprintf('Decrease balance by %d', $value));
return $this->next->dec($value);
}
}
$initialBalance = new \Balance();
$cacheBalance = new \CacheBalance($initialBalance, $cache);
$logBalance = new \LogBalance($cacheBalance, $logger);
$balance = $logBalance;