State Pattern in PHP

The state pattern is a behavioural software design pattern. It is used to allow an object to changes it’s behaviour when it’s internal state changes. Below is an example of the state pattern in PHP. I have taken a stop watch with 2 buttons and implemented the code using the state pattern. The first button will be the start/stop for the timer. The second button will reset the timer back to 0. Each time you hit stop, the code will output the time since it started in milliseconds.

interface State {
    function press(StopWatchContext $context);
}

class StopState implements State {
    public function press(StopWatchContext $context) {
        $time = (microtime(TRUE) * 1000) - $context->getStartTime();
        printf("The stop watch is stopped. [Time] %d MS 
", $time);; $context->setState($context->getStartState()); } } class StartState implements State { public function press(StopWatchContext $context) { echo "The stop watch is running..
"; $context->setState($context->getStopState()); } } class ResetState implements State { public function press(StopWatchContext $context) { echo "The stop watch is reset.
"; $context->setStartTime(microtime(TRUE) * 1000); $context->setState($context->getStartState()); } } class StopWatchContext { private $state; private $startTime; private $startState; private $stopState; private $resetState; public function __construct() { $this->setStartTime(); $this->startState = new StartState(); $this->stopState = new StopState(); $this->resetState = new ResetState(); $this->state = $this->startState; } public function setState(State $state) { $this->state = $state; } public function pressButton() { $this->state->press($this); } public function resetButton() { $this->setState(new ResetState()); $this->pressButton(); } public function getStartTime() { return $this->startTime; } public function setStartTime() { $this->startTime = microtime(TRUE) * 1000; } public function getStartState() { return $this->startState; } public function getStopState() { return $this->stopState; } public function getResetState() { return $this->resetState; } } $timer = new StopWatchContext(); $timer->pressButton(); //started usleep(1200 * 1000); // sleeping 1.2 seconds $timer->pressButton(); //stopped $timer->pressButton(); //started usleep(2000 * 1000); //sleeping 1.7 seconds (3200 MS) $timer->pressButton();//stopped $timer->resetButton(); //reset $timer->pressButton();//started sleep(2);//sleeping 2 seconds $timer->pressButton(); //stopped ?>

:: Output: :
The stop watch is running..
The stop watch is stopped. [Time] 1200 MS
The stop watch is running..
The stop watch is stopped. [Time] 3200 MS
The stop watch is reset.
The stop watch is running..
The stop watch is stopped. [Time] 2000 MS