State is a behavioral design pattern that allows an object to change the behavior when its internal state changes.
The pattern extracts state-related behaviors into separate state classes and forces the original object to delegate the work to an instance of these classes, instead of acting on its own.
Usage examples: The State pattern is occasionally used in PHP for turning large and cumbersome state machines based on switch operators into objects.
Identification: State pattern can be recognized by methods that change their behavior depending on the objects’ state, controlled externally.
Conceptual Example
This example illustrates the structure of the State design pattern and focuses on the following questions:
What classes does it consist of?
What roles do these classes play?
In what way the elements of the pattern are related?
After learning about the pattern’s structure it’ll be easier for you to grasp the following example, based on a real-world PHP use case.
index.php: Conceptual example
Output.txt: Execution result
Real World Example
While the concept of state machines and the State pattern itself are very popular among developers, I can’t think of any decent real-world example of this pattern in a real PHP application.
However, if you’d used the pattern in your project before, feel free to share your experience on the forum or via email support@refactoring.guru. Thanks!