In this first part of a series, I provide a basic introduction to implementing the registry design pattern in PHP. I'll define a simple hierarchy of classes comprised of an abstract registry, and a concrete implementation of it, which uses a private array to save and fetch resources across different points of an application.
Design patterns are well-trusted and reusable paradigms that allow you to solve common problems present in software development. This is not the only benefit to using design patterns. Many design patterns have intuitive names that permit you to grasp fairly easily what they do or what kind of issue they attempt to address. This is especially useful when exchanging ideas and thoughts between members of a development team (or expressed in other terms, the so-called ubiquitous language, also present in domain-driven design).
A good example of a pattern whose name reflects quite faithfully the task that it performs is Registry, As you may have guessed, the implementation of a registry permits you to save a given resource, be it a string, an array or an object, to a predefined storage mechanism in a part of an application, later retrieve the resource at another point in the same application.
Due to its underlying logic, however, the registry pattern has always been the subject of heated debates. Many people, especially in the PHP field, see it as an elegant replacement for global variables, which is a bad, deprecated programming habit.
What’s more, some have been even more rigorous in their judgments and consider the Registry to actually be an antipattern. Well, in my opinion there’s no need to be that rude; indeed, a measured and conscientious implementation of a registry can be really beneficial in certain use cases. Anyway, my intention here is not to add more flames to the existing controversy; that would be pretty pointless.
Instead, it’d be useful to analyze the topic from a didactic point of view. With this premise in mind, in this article series I’m going to demonstrate how to implement the registry pattern in PHP. You'll be able evaluate the pros and cons and learn how to use it (when applicable) in your own object-oriented programs.
Ready to get your hands dirty and start learning how to create flexible registries in PHP? Then jump forward and start reading right now!