Without a doubt, the best way to see how the previous array-based registry class does its business is by example. In consonance with this idea, below I coded a basic script that shows how to use the registry for saving the full name of a fictional user, and then for retrieving the data at a later point. Hereís how this script looks:
// include source classes
// get Singleton instance of the ArrayRegistry class
$arrayRegistry = ArrayRegistry::getInstance();
// save some data to the array registry at one point of the application
$arrayRegistry->set('user1', 'Linda Smith');
// get data from the array registry at some other point of the application
echo 'Full name of user1 : ' . $arrayRegistry->get('user1');
Even though I have to admit that its logic is somewhat simplistic, the above example shows how to employ this sample array registry class in a pretty useful fashion. In this particular case, the resource being saved and retrieved at a later time is a plain string, but itís possible to do the same thing with other types of data, including arrays, objects and so forth.
Again, itís clear to see here that the registry pattern provides global access (with some restrictions) to one or multiple resources at different places in an application, so at the risk of being redundant, make sure to implement it only when you really need to take advantage of its functionality.
Feel free to edit and introduce your own improvements to all of the sample classes shown in this tutorial. In doing so, youíll acquire a better understanding of how to more efficiently apply the registry pattern in PHP using an object-oriented approach.
In this first part of the series, I provided you with a basic introduction to implementing the registry design pattern in PHP. In this particular case I decided to accomplish this process by defining a simple hierarchy of classes composed of an abstract registry, and a concrete implementation of this, which uses a private array to save and fetch resources across different points of an application.
For obvious reasons, creating an abstract registry and deriving a single subclass from it is a pretty pointless process that doesnít take full advantage of the benefits offered by Inheritance. To address this issue, in the following tutorial Iím going to spawn yet another registry class from the parent, which will behave like a simple session handler.
Want to see how this brand new registry class will be created? Then donít miss the next part!
blog comments powered by Disqus