Registry Design Pattern

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!

{mospagebreak title=Defining an abstract registry class}

As I said in the introduction, the goal of the registry pattern is simply to provide client code with a mechanism which allows you to save and retrieve resources across different points of an application. Even though its implementation in PHP (and other languages) may vary from case to case, in general creating a basic registry using an object-oriented approach demands that you build a class containing the methods required to perform the saving/retrieval tasks.

In consonance with the previous concepts, first I’m going to demonstrate how to apply the pattern in question by of creating an abstract registry class, whose concrete implementations (read: their eventual subclasses) will be tasked with storing and fetching resources by means of different persistence mechanisms.

Having said that, here’s the definition of this abstract registry. Look at it, please: 

(AbstractRegistry.php)

 

 

<?php

 

abstract class AbstractRegistry

{  

    protected static $_instances = array();

   

    // get Singleton instance of the registry (uses the ‘get_called_class()’ function available in PHP 5.3)

    public static function getInstance()

    {

        // resolves the called class at run time

        $class = get_called_class();

        if (!isset(self::$_instances[$class]))

        {

            self::$_instances[$class] = new $class;

        }

        return self::$_instances[$class];

    } 

   

    // overriden by some subclasses

    protected function __construct(){}

   

    // prevent cloning instance of the registry

    protected function __clone(){}

   

    // implemented by subclasses   

    abstract public function set($key, $value);

   

    // implemented by subclasses

    abstract public function get($key);

   

    // implemented by subclasses

    abstract public function clear();  

}

If you closely analyze the above “AbstractRegistry” class, you’ll see that it’s nothing but a Singleton that defines a basic interface, whose methods must be properly implemented by all the concrete registries derived from it. I decided to make this abstract class a Singleton to restrict the point of access to each concrete registry; this small constraint, however, doesn’t prevent them from being used globally at different points of an application. Again, a word of warning is in order here: due to the global nature of the pattern, it should be applied with caution and responsibility.

In addition, you may have noticed that the previous “getInstance()” method calls internally the “get_called_class()” function, available from PHP 5.3, which uses Late Static Bindings to determine at runtime which registry class should be invoked in a static context. This function makes creating hierarchy of Singletons a breeze, but if you still haven’t made the upgrade to that version of PHP, you’ll either have to implement this method within each concrete registry (a very annoying and inefficient approach) or make those registries non-Singletons.

So far, so good. With an abstract registry neatly accommodated on top of the hierarchy, we now need to derive a concrete class from this parent, which permits us to save and fetch resources from a specific storage mechanism.

With that idea in mind, in the following section I’m going to create a concrete registry that will save and retrieve a given resource from a plain array. To see how this whole new class will be defined, click on the link below and keep reading.             

{mospagebreak title=Building an array-based registry}

To be frank, building a Singleton array-based registry is indeed a straightforward process that can be mastered with minor hassles. Still not convinced of this? Well, in that case take a look at the definition of the following class, which hopefully will make your doubts vanish. Here it is:

(ArrayRegistry.php)

 

 

<?php

 

class ArrayRegistry extends AbstractRegistry

{

    private $_data = array();

                 

    // save new data to the array registry

    public function set($key, $value)

    {

        $this->_data[$key] = $value;

    }

   

    // get data from the array registry

    public function get($key)

    {

        return isset($this->_data[$key]) ? $this->_data[$key] : NULL;

    }

   

    // clear the state of the array registry

    public function clear()

    {

        $this->_data = array();

    }    

}

There you have it. As you can see, creating a class that stores and fetches resources from an array is a painless task, one that you may have done many times before. In this case, this concrete registry not only implements the abstract methods declared by its corresponding parent, but it also inherits from it the “getInstance()” Singleton, thanks to the functionality of Late Static Bindings. That was really simple to grasp, wasn’t it?

If you’re planning to build a registry that fits more specific requirements, the one shown above should be enhanced accordingly by adding to it some constraints, especially within its “set()” method. For instance, you might want to make the registry only suitable for storing/retrieving objects; in a case like this, make sure to include the appropriate validation code into this method, and everything should work just fine.

Well, now that we have a concrete registry available for testing purposes, it’s time to give it a try and see if it really works as expected. So, in the next segment I’m going to set up an example that will show the registry’s functionality in a few simple steps.

To learn more about how this example will be developed, jump forward and read the lines to come.

{mospagebreak title=Putting the array-based registry to work}

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

require_once ‘AbstractRegistry.php’;

require_once ‘ArrayRegistry.php’;

 

 

// 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.     

Final thoughts

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!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan