Introducing the Chain of Responsibility Between PHP Objects

This article, the first of three parts, introduces you to the chain of responsibility pattern in PHP 5. This pattern is useful when a specific class cannot deal with a particular task, and must therefore transfer a program’s execution to another class with the appropriate capability.

Very often during the development of a web application with PHP, you probably found yourself creating a wealth of classes that have a predefined scope of action where they will be instantiated, and present a carefully-crafted grade of responsibility as well. Although most of the time, this scenario makes more sense than having a well-planned interaction between different objects, there are situations where things aren’t so clear, particularly when trying to define the range of specific tasks that must be performed by certain classes.

To put this into perspective, let me cite a concrete example that hopefully will allow you to understand more clearly what I’m talking about here. Suppose that you have created a useful MySQL wrapping class, which obviously is capable of connecting to the server, running queries, selecting databases and so forth. So far, this case is quite familiar to you, isn’t it? Now let me go one step further and ask you the following question: what’s the best approach to take when it comes to handling result sets?

Is it better to implement the logic required for processing data sets as part of the same class, or to build a new class that will handle independently all the returned database rows?

Certainly, from my personal point of view, I’d follow the latter approach, simply because it allows the scope of responsibility established between the mentioned classes to be much better delimited, as well as their respective interdependencies. However, when building an isolated result set processing class, this approach might not eventually be capable of dealing with certain conditions, such as formatting database rows as XML, to cite a concrete example.

Therefore, it would be necessary to create another class that would be responsible for returning to calling code differently-formatted result sets to keep the scope of all the classes clearly defined. Now, do you grasp my point with this example? As you can see, there are times when a specific class may not be capable of dealing with a given task, and therefore must transfer the program’s execution to a different one which potentially will solve the problem in question.

True to form, the situation that I just described above is commonly known by many programmers as the “chain of responsibility between objects” or more simply, the chain of responsibility pattern. It deserves an in-depth look to explore its advantages in real situations.

Therefore, in this three-part series, I’ll show you how to create a chain of responsibility across different classes, which hopefully will give you a better understanding of how this schema can be implemented with PHP. Are you ready to learn more on this topic? All right, let’s go!

{mospagebreak title=The why and how of the chain of responsibility}

Naturally, it’s good to learn how a predefined chain of responsibility can be created across several PHP classes by setting up a comprehensive example. This will help you to grasp the basic concepts of this theme.

To begin with, I’ll define a group of simple classes, tasked with saving different types of data to a specified text file. Each class will be capable of delegating the execution of a particular process to its nearest parent when the current class is incapable of handling the process in question. That being said, here is the definition of the base “AbstractDataSaver” class, which will set up the blueprints for all of its respective sub classes:

// define abstract ‘AbstractDataSaver’ class
abstract class AbstractDataSaver{
    abstract public function getFilePath();
    abstract public function setData($data);
    abstract public function getData();
    abstract public function saveData();

}

In this case, the skeleton of the above abstract class exposes the core methods that will be concretely implemented by the respective children. Here, it’s clear to see that each of these abstract methods conform to a generic model, which is handy for defining (in a later section) the structure of a few concrete classes that will be capable of storing distinct data on plain text files.

With reference to the signature of the prior “AbstractDataSaver” class, you can see that it first defines a “getFilePath()” method, which will eventually return the path of the text file to where the data will be saved. Next, it defines a set of additional methods, called “setData()”, “getData()” and “saveData()” respectively, tasked with accessing and modifying the data in question, as well as saving it to the mentioned file.

Now that you have learned how the above class was defined, pay attention to the following one. It is obviously a subclass, and implements concretely each of the abstract methods declared before.

The signature of this new class is listed below:

// define concrete ‘DataSaver’ class on top of the chain of
responsibility
class DataSaver extends AbstractDataSaver{
    private $filePath;
    private $data;
    public function __construct($filePath){
        $this->filePath=$filePath;
        $this->data=NULL;
    }
    public function getFilePath(){
        return $this->filePath;
    }
    public function getData(){
        if($this->data==NULL){
            throw new Exception(‘No data has been set for being
saved to file!’);
        }
        return $this->data;
    }
    public function setData($data){
        $this->data=$data;
    }
    public function saveData(){}
}

Undoubtedly, there are some interesting things to be said about the brand new sub class shown above. First, as I said before, it implements the majority of the abstract methods that were initially declared in the base class, and then defines the top of the chain of responsibility that will be implemented by its corresponding child classes.

If this last concept sounds rather confusing to you, please take a look at the definition of the pertinent “getData()” method:

public function getData(){
    if($this->data==NULL){
        throw new Exception(‘No data has been set for being saved
to file!’);
    }
    return $this->data;
}

Essentially, the signature for this method actually consists of an important block within the chain of responsibility schema, since it demonstrates in a nutshell how the absence of the $this->data property (in this case represented by the condition $this->data==NULL) will be handled simply by throwing a new exception, and eventually stopping the application’s execution.

As you’ll see over the course of the sections to come, all the child classes that will be derived from “AbstractDataSaver” will try to handle the lack of the referenced $this-> data property either on their own or by calling their parent class, instead of triggering an error. This fact really establishes a well-defined chain of responsibility between all the classes; when this condition can’t be handled by the current class, it will be delegated to the corresponding parent. Quite good, right?

Having explained the course of action that will be taken by the previous “DataSaver” class when the $this>data property that you learned before is null, it’s time to leap forward. In the next section, we will see how the remaining sub classes that integrate the lower levels of the corresponding responsibility chain will be properly defined. 

{mospagebreak title=Creating a few sub classes}

Creating the respective sub classes that reside on the lower levels of the mentioned responsibility chain is in fact a straightforward process that can be performed with minor problems. This procedure is limited to deriving a pair of child classes from the “AbstractDataSaver” class shown in the previous section, and coding their respective “getData()” methods in such a way that they can delegate the program flow to the parent class when they can’t handle the absence of the mentioned $this->data property by themselves.

Of course, you’ll understand this concept much better if you take a look at the definition of the new sub class below:

// define ‘ArraySaver’ class
class ArraySaver extends AbstractDataSaver{
    private $filePath;
    private $data;
    private $parentDataSaver;
    public function __construct($filePath,DataSaver
$parentDataSaver){
        $this->filePath=$filePath;
        $this->data=NULL;
        $this->parentDataSaver=$parentDataSaver;
    }
    // get path for data file
    public function getFilePath(){
        return $this->filePath;
    }
    // get array of data
    public function getData(){
        if($this->data==NULL){
            // call parent object in chain of responsibility
            return $this->parentDataSaver->getData();
        }
        else{
            return $this->data;
        }
    }
    // set array of data
    public function setData($data){
        if(!is_array($data)){
            throw new Exception(‘Data must be an array!’);
        }
        $this->data=$data;
    }
    // save array to file
    public function saveData(){
        if(!$fp=fopen($this->getFilePath(),’w')){
            throw new Exception(‘Error opening data file!’);
        }
        if(!fwrite($fp,serialize($this->getData()))){
            throw new Exception(‘Error saving array to data
file!’);
        }
        fclose($fp);
    }
}

After listing the definition of the above “ArraySaver” class, you’ll probably know what it does. To put it simply, this new sub class takes up an input array and saves it to a given text file. Simple, right? However, I’d like you to pay careful attention to the signature of all its methods, but more specifically to the following one:

public function getData(){
    if($this->data==NULL){
        // call parent object in chain of responsibility
        return $this->parentDataSaver->getData();
    }
    else{
        return $this->data;
    }
}

As you can see, the “getData()” method handles the absence of the $this->data property in a slightly different manner than the one shown when the parent “DataSaver” class was defined. More specifically, this method will call the mentioned parent when it is unable to handle this condition on its own. In this way it transfers the responsibility for dealing with the problem in question toward the upper element placed inside the chain.

Now do you realize how the a predefined responsibility chain can established across several PHP classes? I bet you do!

At this stage, and after understanding properly how the previous sub class works, let’s move on to the following section. I will show you how another child class can be created so that we have at least two elements that implement the chain of responsibility that I discussed before.

Sounds interesting, doesn’t it? Click on the below link and keep reading.

{mospagebreak title=Completing the chain of responsibility}

In this case, since I wish to have at hand another sub class that eventually moves the program’s execution up the chain of responsibility, I’ll simply define a new child class, which will be tasked with saving plain strings to a given text file. Not surprisingly, the signature of this class is extremely simple and looks like this:

// define ‘StringSaver’ class
class StringSaver extends AbstractDataSaver{
    private $filePath;
    private $data;
    private $parentDataSaver;
    public function __construct($filePath,DataSaver
$parentDataSaver){
        $this->filePath=$filePath;
        $this->data=NULL;
        $this->parentDataSaver=$parentDataSaver;
    }
    // get path for data file
    public function getFilePath(){
        return $this->filePath;
    }
    // get string of data
    public function getData(){
        if($this->data==NULL){
            // call parent object in chain of responsibility
            return $this->parentDataSaver->getData();
        }
        else{
            return $this->data;
        }
    }
    // set string of data
    public function setData($data){
        if(!is_string($data)){
            throw new Exception(‘Data must be a string!’);
        }
        $this->data=$data;
    }
    // save string to file
    public function saveData(){
        if(!$fp=fopen($this->getFilePath(),’w')){
            throw new Exception(‘Error opening data file!’);
        }
        if(!fwrite($fp,$this->getData())){
            throw new Exception(‘Error saving array to data
file!’);
        }
        fclose($fp);
    }
}

If you consider that the logic implemented by the previous “ArraySaver” sub class was really easy to understand, then you’ll find the behavior followed by the above class even simpler.

Please notice how its “getData()” method also calls the corresponding parent class (inputted via the respective constructor) when it’s not possible to handle the absence of the $this->data property. This is nearly identical to the approach followed by the other “ArraySaver” sub class, defined opportunely in the previous section.

All right, I strongly believe that the two subclasses that you learned before are more than enough to give you a correct understanding of how a specific chain of responsibility can be established between a group of PHP classes.

Considering this situation, in the final section of this article I’ll show you how all these classes can interact with each other, implementing the chain of responsibility that I discussed right from the very beginning of this article.

Want to learn how this will be achieved? Then go ahead and click on the link below.

{mospagebreak title=Making the chained classes work together}

As I said in the section you just read, the simplest way to see whether the chain of responsibility really works consists of developing a concrete example where all the previously defined classes are put to work conjunctly. Therefore, I’ll begin listing a short script. It will show the behavior followed by the first class, that is “DataSaver,” before and after assigning a value to the $this->data property. Please take a look:

try{
    // instantiate ‘DataSaver’ object
    $dataSaver=new DataSaver(‘defaultPath/default_datafile.txt’);
    // call ‘getData()’ method without setting its $data property
    echo ‘DataSaver class outputs the following without setting data property:<br />’;
    $dataSaver->getData();
    /* displays the following:
    DataSaver class outputs the following without setting data
property:
    No data has been set for being saved to file!
    */
    // assign a value to $data property
    echo ‘DataSaver class outputs the following when $data
property has been set:<br />’;
    $dataSaver->setData(‘This is the string of data that will be
saved to file.’);
    echo $dataSaver->getData();
    /* displays the following:
    DataSaver class outputs the following when $data property has
been set:
    This is the string of data that will be saved to file.
    */
}
catch(Exception $e){
    echo $e->getMessage();
    exit();
}

As you can see, before assigning a value to the $this->data property, the script throws an exception and its execution is halted. On the other hand, when a new value is assigned to the property in question, the snippet displays an indicative message. Since the “DataSaver” class is seated on top of the responsibility chain, the behavior shown above is simply expected.

Now, take a deep breath and look at the following two examples, which demonstrate how the corresponding child classes delegate the responsibility to their parent when they can’t deal with the specific situation where the value assigned to the $this->data property is null:

try{
    // instantiate ‘DataSaver’ object
    $dataSaver=new DataSaver(‘defaultPath/default_datafile.txt’);
    // instantiate ‘ArraySaver’ object
    $arraySaver=new ArraySaver(‘defaultPath/default_datafile.txt’,$dataSaver);
    // try to save data without setting $data property
    echo ‘DataSaver class outputs the following without setting
the value of $data property:<br />’;
    $arraySaver->saveData();
    /*
    // displays the following:
    DataSaver class outputs the following without setting the
value of $data property:
    No data has been set for being saved to file!
    */
    // assign value to $data property
    echo ‘ArraySaver class outputs the following when $data
property has been set:<br />’;
    $arraySaver->setData(array(‘This is element 1′,’This is
element 2′,’This is element 3′));
    $arraySaver->saveData();
    print_r($arraySaver->getData());
    /*
    displays the following:
    ArraySaver class outputs the following when $data property
has been set:
    Array ( [0] => This is element 1 [1] => This is element 2 [2]
=> This is element 3 )
    */
}
catch(Exception $e){
    echo $e->getMessage();
    exit();
}
try{
    // instantiate ‘DataSaver’ object
    $dataSaver=new DataSaver(‘defaultPath/default_datafile.txt’);
    // instantiate ‘StringSaver’ object
    $stringSaver=new StringSaver(‘defaultPath/default_datafile.txt’,$dataSaver);
    // try to save data without setting $data property
    echo ‘StringSaver class outputs the following without setting
the value of $data property:<br />’;
    $stringSaver->saveData();
    /*
    displays the following:
    StringSaver class outputs the following without setting the
value of $data property:
    No data has been set for being saved to file!
    */
    // assign value to $data property
    echo ‘ArraySaver class outputs the following when $data
property has been set:<br />’;
    $stringSaver->setData(‘This string of data will be saved to
file.’);
    $stringSaver->saveData();
    echo $stringSaver->getData();
    /*
    displays the following:
    ArraySaver class outputs the following when $data property
has been set:
    This string of data will be saved to file.
    */
}
catch(Exception $e){
    echo $e->getMessage();
    exit();
}

Indeed, after examining the above examples, you’ll have to agree with me that the chain of responsibility works like a charm! Try creating your own PHP classes and implement the same schema to see what happens in each case.

Wrapping up

In this first article of the series, you learned the basics of defining a chain of responsibility between several PHP classes to handle a specific task. Hopefully, the hands-on examples shown here will give you some useful pointers to get started on this subject quickly.

In the next tutorial, I’ll show you how to apply a responsibility chain across different PHP classes, which is handy for developing an error login system. Meet you in the next part!

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