Skip to content

Instantly share code, notes, and snippets.

@darraghenright
Created September 11, 2013 07:53
Show Gist options
  • Save darraghenright/6520512 to your computer and use it in GitHub Desktop.
Save darraghenright/6520512 to your computer and use it in GitHub Desktop.
<?php
interface TurnstileInterface
{
public function insertCoin();
public function pass();
}
class Turnstile implements TurnstileInterface
{
private $state;
private $opened;
private $closed;
function __construct()
{
$this->opened = new TurnstileStateOpened();
$this->closed = new TurnstileStateClosed();
$this->state = $this->closed;
}
public function insertCoin()
{
$this->state->insertCoin();
$this->state = $this->opened;
}
public function pass()
{
$this->state->pass();
$this->state = $this->closed;
}
}
class TurnstileStateOpened implements TurnstileInterface
{
public function insertCoin()
{
throw new Exception('Coin already inserted!' . PHP_EOL);
}
public function pass()
{
echo 'pass! the gate is open!' . PHP_EOL;
}
}
class TurnstileStateClosed implements TurnstileInterface
{
public function insertCoin()
{
echo 'thanks! opening the gate!' . PHP_EOL;
}
public function pass()
{
throw new Exception('Alarm! Security!' . PHP_EOL);
}
}
$turnstile = new Turnstile();
$turnstile->insertCoin();
$turnstile->pass();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment