Visitor is a behavioral design pattern that allows adding new behaviors to existing class hierarchy without altering any existing code.
Read why Visitors can’t be simply replaced with method overloading in our article Visitor and Double Dispatch.
Application of the pattern in PHP
Usage examples: The Visitor pattern isn’t very common in PHP code because of its complexity and narrow applicability.
Example: Structure of the Pattern
This example illustrates the structure of the Visitor 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.
VisitorStructural.php: Structural Example
Example: Real World Example
In this example, the Visitor pattern helps to introduce a reporting feature into an existing class hierarchy:
Company > Department > Employee
Once the Visitor infrastructure is added to the app, you can easily add other similar behaviors to the app, without changing the existing classes.
VisitorRealWorld.php: Real world example