HomePHP Session Handler with the Registry Design Pattern
Session Handler with the Registry Design Pattern
In this second part of a series, I demonstrate how easy it is to define a session-based registry class based on the abstract parent created in the first tutorial. The straightforward creation process means you shouldn’t have major problems building your own registry classes or even improving the ones that you've learned so far in this series.
Even now, many PHP developers are reluctant to implement the registry design pattern. Using the pattern seems similar to using the "evil" and deprecated global variables. But the truth is that, when used in a conscientious and responsible manner, the pattern can be really helpful. Its functionality allows you to retrieve and save resources (usually objects, although other data types are valid as well) throughout different points of an application using a predefined storage mechanism.
What's more, implementing the pattern in PHP is such an approachable process that it's possible to create all sorts of registries even if you have only an average background in classes and objects. It's that simple, really.
This doesn't mean, however, that registries should be considered outdated structures that must be deprecated in favor of more effective solutions. In fact, some well-established, enterprise-level frameworks, including one of the most well-known contenders in the field, namely the Zend Framework (http://framework.zend.com), implements a static registry via its Zend_Registry component. This can be manipulated at will by means of a neat variety of options.
Of course, you don't need to build an entire framework from scratch to understand the logic that stands behind the registry pattern. To prove that point, in the preceding part of this article series I went thought the development of a simple hierarchy composed of two basic classes. The first one was an abstract Singleton that defined the structure of generic registries, and the second one was a refined implementation of the abstract parent, tasked with saving and fetching resources by using a private array.
While this sample hierarchy of classes does a decent job of illustrating how functional registries can be when implemented with some constraints, it'd be useful to create yet another registry class that uses a mechanism different from plain arrays to fetch and store resources across several points of an application. With that idea in mind, in this second chapter of the series I'm going to demonstrate how to build an additional registry, which will behave like a simple session handler.
Now, let's start building the session-based registry.