10.1. Problem and Solution

The Interpreter Design Pattern is one of the few extremely common design patterns you may have been using often without realizing it. This style of design is not limited to just the creation of classes. The base concepts of the Interpreter Design Pattern are used throughout most of the programming algorithms created.

To understand how the Interpreter Design Pattern works, consider the processing of a macro language. The commands that are written for each macro are, in themselves, collections of more commands. The shorthand macro language makes it easier for a programmer to create something without having to worry about the exact syntax of other system commands. In some cases, this is also done to boost security: the programmer is not given direct access to the system commands. Instead, wrapper methods are written to execute the system commands in a sort of sandbox. The macro language is interpreted and translated into a set of commands to be executed.

Another way to think of this is by examining a template system. Specific predefined keywords or symbols are defined to represent something else. The template processor takes the code, interprets each keyword to reference a specific set of instructions, and executes those.

Building systems based around the Interpreter Design Pattern allows third parties or users greater flexibility over how to present and retrieve data that the system provides. Instead of predefining method names or specific constants to ...

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.