HomePHP Page 4 - Introducing the Chain of Responsibility Between PHP Objects
Completing the chain of responsibility - PHP
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.
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.