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 original object to delegate the work to an instance of these classes, instead of acting on its own.
Application of the pattern in PHP
Usage examples: The State pattern is occasionally used in PHP for turning large and cumbersome state machines based on
switch operators into objects.
Example: Structure of the Pattern
This example illustrates the structure of the State design pattern and focuses on following questions:
- What classes does it consists 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.
StateStructural.php: Structural Example
Example: 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 email@example.com. Thanks!