State Pattern example in PHP
The State pattern is excellent for making the behavior of an object dependent on its state. 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
If you call the class with
it gets the state Stop by the constructor. This means we can switch from this state to the Open state.
Now, I try this
An error will happen
because the door must first be closed.
The complete source of this example is available on GitHub.
If you liked this post, you can share it with your followers or ping me on Twitter!