19.1. Problem and Solution

The Visitor Design Pattern helps take the complexity out of base objects. Basically, it is a separation of the algorithm from the object that it applies to. This seems to be a common goal of a lot of the design patterns in this book. However, the Visitor Design Pattern tackles this in a unique way.

The name Visitor has been given to this design pattern for a reason. While some other approaches to designing self-contained algorithm classes apply themselves externally, the Visitor object is designed to be incorporated into the object it intends to modify. After visiting or entering the object, a standard method call is executed with an instance of the base class being sent into that Visitor class. Because of this, the Visitor Design Pattern enforces a unified way of accessing these visiting objects' logic. Basically, each Visitor is asked the same thing, but what they do internally to accomplish the task is different.

One of the major benefits of this design pattern is the ability to add new functionality to an object without modifying that object. If the base object is built to accept Visitors, any new bit of logic can be applied through the Visitor acceptance method. Unit tests on the base object never need to be changed. Any new functionality is in the form of Visitors who are distinct from the base object and have their own testing methods. This provides a great flexibility for future development: any new feature set will be constructed as a visit ...

Get Professional PHP Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.