Home arrow PHP arrow Page 4 - Building an Error Logger with the Chain of Responsibility Pattern in PHP 5

Logging email-related errors - PHP

If you’re one of those PHP developers that wants to expand your background in pattern-based programming, then this article may suit your needs. Welcome to the second part of the series “Understanding the Chain of Responsibility Between PHP Objects.” Comprised of three installments, this series goes through the basics of building a chain of responsibility across several PHP objects, and teaches you how to apply this pattern by using copious code samples.

TABLE OF CONTENTS:
  1. Building an Error Logger with the Chain of Responsibility Pattern in PHP 5
  2. Setting up the foundations of an error logger
  3. Logging specific errors at a lower level
  4. Logging email-related errors
By: Alejandro Gervasio
Rating: starstarstarstarstar / 4
November 06, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: