Expanding an Error Logger with the Chain of Responsibility Pattern - The error logging system in action (
Page 5 of 5 )
If you're like me, then you'll think that the best way of understanding how the error logging system works is by developing a comprehensive example which uses all the classes in conjunction.
Therefore, below you'll see a simple script I coded that shows the respective behaviors followed by all the classes defined over the previous sections, whether or not a concrete error logger has been set. Please look at this handy group of examples:
try{
// instantiate 'ErrorLogger' object
$errorLogger=new ErrorLogger();
// validate email without providing an error logger
$errorLogger->getErrorLogger();
/*
displays the following:
No error logger has been set!
*/
}
catch(Exception $e){
echo $e->getMessage();
exit();
}
try{
// instantiate 'ErrorLogger' object
$errorLogger=new ErrorLogger();
// instantiate 'FileErrorLogger'
$fileErrorLogger=new FileErrorLogger($errorLogger);
// instantiate 'EmailValidator' object
//$emailValidator=new EmailValidator('username@domain.com',$fileErrorLogger);
//$emailValidator->validate();
/*
displays the following:
No error logger has been set!
*/
}
catch(Exception $e){
echo $e->getMessage();
exit();
}
try{
// instantiate 'ErrorLogger' object
$errorLogger=new ErrorLogger();
// provide an error logger
$fileErrorLogger=new FileErrorLogger($errorLogger);
$fileErrorLogger->setErrorLogger('File Error Logger');
$emailValidator=new EmailValidator('username@domain.com',$fileErrorLogger);
$emailValidator->validate();
}
catch(Exception $e){
echo $e->getMessage();
exit();
}
As shown above, the first two examples demonstrate clearly how the chain of responsibility is moved up toward the base "ErrorLogger" class when an appropriate error logger isn't provided to the scripts. This condition is reflected by the outputs generated by each script, since they complain loudly about this condition by displaying the following message:
No error logger has been set!
Finally, the last example illustrates a concrete case where a "FileErrorLogger" object is injected straight into the respective "EmailValidator" class. As you'll realize, this fact obviously allows the correct implementation of its "validate()" method. As usual, I suggest you to try modifying the previous examples and see what happens in each case.
Final thoughts
I'm finished now. In this three-part series, I introduced you to the basics of how to implement the chain of responsibility pattern with PHP 5. I hope that all the examples that were shown in this set of articles will help you start applying this schema in your own PHP applications. See you in the next PHP tutorial!