Building an Error Logger with the Chain of Responsibility Pattern in PHP 5 - Setting up the foundations of an error logger
(Page 2 of 4 )
In order to start building the error logging system that I mentioned in the beginning, first I'll create a pair of classes that will sit on top of the responsibility chain. They'll be responsible for defining the blueprints for all the eventual sub classes that will be derived from them.
Obviously, any potential errors that can't be logged by the corresponding child modules will be delegated to the respective parent, in this way implementing the so-called chain of responsibility. That being said, here is the signature for the first couple of base classes that I mentioned before:
// define abstract 'AbstractErrorLogger' class on top of the
responsibility chain
abstract class AbstractErrorLogger{
abstract public function setErrorLogger($errorLogger);
abstract public function getErrorLogger();
abstract public function logError();
}
// define concrete 'ErrorLogger' class
class ErrorLogger extends AbstractErrorLogger{
private $errorLogger;
public function __construct(){
$this->errorLogger=NULL;
}
// get error logger
public function getErrorLogger(){
if($this->errorLogger==NULL){
throw new Exception('No error logger has been set!');
}
return $this->errorLogger;
}
// set error logger
public function setErrorLogger($errorLogger){
$this->errorLogger=$errorLogger;
}
public function logError(){}
}
If you examine the respective definitions of the classes listed above, then you'll understand quickly what they do. Basically, the first base class has been declared abstract, and in accordance with this concept, defines the generic structure of any error logger sub class that may be potentially derived from it.
With reference to the second class, it implements in a concrete way many of the methods declared in its abstract parent, except for the one called "logError()." Nevertheless, I want you to turn your attention to the logic followed by the "getErrorLogger()" method. As you can see, it defines the top of the responsibility chain; if an appropriate error logger isn't found (represented by the condition $this->errorLogger==NULL), it simply throws an exception and the program's execution is eventually halted.
Clearly, the behavior exposed by the previous class is a notorious sign that there must be other error loggers that need to be created to define the lower levels of the corresponding responsibility chain.
Based upon this premise, and after defining the structure of the generic error logger that you saw before, the next step consists of precisely deriving a new sub class from the base class in question. Therefore, the chain of responsibility can be provided with an extra module which will be tasked with logging specific errors.
To see how this brand new error logger will be defined, click on the link below and keep reading.
Next: Logging specific errors at a lower level >>
More PHP Articles
More By Alejandro Gervasio