The State pattern is a solution to the problem of how to make behavior depend on state. Here is a simple State Pattern example in PHP.
In my example, it is an elevator that can have the following states:
- Open (Open)
- Closed (Close)
- In Motion (Move)
- Stand (Stop)
From this, the following interface can be derived
Now we need a class ElevatorState that implements the interface
By default, all methods throw an exception. In my case it is an IllegalStateTransitionException which inherits from LogicException.
Now we can implement the individual states. In this example, the Move state.
As you can see, not all methods are implemented from ElevatorState.
Exactly this, which are not allowed for the current state.
The class Elevator
Now, you can create a new Elevator instance.
This works, because each step is allowed by its predecessor as the next step.
PHP Fatal error: Uncaught Elevator\Exception\IllegalStateTransitionException
It doesn’t work because “Move” is not allowed when the elevator is “Open”.
The complete source of this example is available on GitHub.
Check out the source code and run
composer install && ./vendor/bin/phpunit tests