PHP
  Home arrow PHP arrow Page 4 - Building an Error Logger with the Chain of Responsibility Pattern in PHP 5
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
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? 
Google.com  
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: starstarstarstarstar / 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:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log 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!



     
     
    >>> More PHP Articles          >>> More By Alejandro Gervasio
     

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek