PHP
  Home arrow PHP arrow Page 4 - Building an Error Logger with the Chai...
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Building an Error Logger with the Chain of Responsibility Pattern in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 4
    2006-11-06

    Table of Contents:
  • Building an Error Logger with the Chain of Responsibility Pattern in PHP 5
  • Setting up the foundations of an error logger
  • Logging specific errors at a lower level
  • Logging email-related errors

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Building an Error Logger with the Chain of Responsibility Pattern in PHP 5 - Logging email-related errors


    (Page 4 of 4 )

    If you're anything like me, then I'm sure that you want to see how the prior "MailErrorLoger" class works in a real situation. Therefore I coded a new sample class (shown below) which essentially performs a decent validation on a given email address that has been previously inputted via its constructor.

    That said, the definition for the email checking class looks like this:

    // define 'EmailValidator' class
    class EmailValidator{ 
        private $email; 
        private $mailErrorLogger; 
        public function __construct($email,ErrorLogger
    $mailErrorLogger){
            $this->mailErrorLogger=$mailErrorLogger; 
            if(!preg_match("/^.+@.+$/",$email)){ 
                $this->mailErrorLogger->logError(); 
            } 
            $this->email=$email; 
        } 
        // validate email 
        public function validate(){ 
            if(!$this->windnsrr(array_pop(explode("@",$this-
    >email)))){
                $this->mailErrorLogger->logError(); 
            } 
        } 
        // check for MX records in the DNS (Windows-based systems) 
        private function windnsrr($hostName,$recType=''){ 
            if(!$hostName){ 
                if($recType=='')$recType="MX"; 
                exec("nslookup -type=$recType $hostName",$result); 
                foreach($result as $line){ 
                    if(preg_match("/^$hostName/",$line)){ 
                        return true; 
                    } 
                } 
                return false; 
            } 
            return false; 
        }
    }

    As shown above, the "EmailValidator" class has been provided with a single method, not surprisingly called "validate()," which comes in very handy for checking whether a given email address is valid or not. This method runs only on Windows-based systems, but it can be easily modified to extend its range of utilization to other operating systems.

    Additionally, it should be noticed that this email checking class accepts an error logger object as one of its input parameters (the other is the email address for validation), which is very convenient for registering errors when a particular email address is considered invalid. As you'll realize, this process is performed inside the respective "validate()" method, and certainly is very easy to follow.

    All right, at this point I think that you grasped the logic that drives the "EmailValidator" class. Let me show you a group of code samples which will demonstrate how this validation mechanism can be used in conjunction with the "MailErrorLogger" class that you learned in the previous section.

    In these examples, if a given email address is considered not valid, and an error logger isn't passed to the email error logging class, then this class will transfer this condition to its parent so that the failure can be appropriately handled. After all, this is how the chain of responsibility works, right?

    Now, take a look at the scripts below:

    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 'EmailErrorLogger' 
        $mailErrorLogger=new MailErrorLogger($errorLogger); 
        // instantiate 'EmailValidator' object 
        $emailValidator=new EmailValidator
    ('username@domain.com',$mailErrorLogger);
        $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 
        $mailErrorLogger=new MailErrorLogger($errorLogger); 
        $mailErrorLogger->setErrorLogger('Email Error Logger'); 
        $emailValidator=new EmailValidator
    ('username@domain.com',$mailErrorLogger);
        $emailValidator->validate();
    }
    catch(Exception $e){ 
        echo $e->getMessage(); 
        exit();
    }

    As you can see, the first two code snippets show what happens when a particular error logger hasn't been defined. In the first case, since none of the pertinent child classes have been instantiated, the parent class handles this situation by throwing an exception and halting the script's execution.

    The second example is slightly more interesting, due to the fact that a "MailErrorLogger" object is created, but no error logger is defined via its "setErrorLogger()" method. This condition is also transferred to the parent, which triggers a new exception.

    The last example shows a case where the correct error logger has been set, therefore the inputted email address can be appropriately verified by the corresponding "validate()" method, and the responsibility for logging errors rests only on the proper "MailErrorLogger" object.

    As you'll realize, when all the previous classes work together, the chain of responsibility schema really works. I suggest you try modifying the above examples and examine the results that you obtain in each situation.

    Wrapping up

    In this second article of the series, I provided you with a more useful example of how to implement a chain of responsibility across a pair of PHP classes, in order to build an error logger system.

    However, this journey isn't finished yet. In the last article, I'll show you how to expand the error logger mechanism that you learned here, by adding more elements to the existing responsibility chain. You won't want to miss it!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · In this second part of the series, the chain of responsibility pattern is applied,...
     

       

    PHP ARTICLES

    - Authentication Scripts for a User Management...
    - Utilizing the Use Keyword for Namespaces in ...
    - Building a User Management Application
    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway
    Stay green...Green IT