Skip to content

Instantly share code, notes, and snippets.

@darraghenright
Created September 11, 2013 07:53
Show Gist options
  • Select an option

  • Save darraghenright/6520512 to your computer and use it in GitHub Desktop.

Select an option

Save darraghenright/6520512 to your computer and use it in GitHub Desktop.

Revisions

  1. darraghenright created this gist Sep 11, 2013.
    63 changes: 63 additions & 0 deletions turnstile.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,63 @@
    <?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();