Centralizing the Validation of Data with the Observer Pattern in PHP

Are you looking for an easygoing article that teaches you how to implement the Observer design pattern inside your PHP 5 applications? Your search is finished! Welcome to the last part of the series “The Observer Pattern in PHP.” Made up of three articles, this series will show you how to create and work with observer objects, without making you scratch your head while looking at complex code samples.

Introduction

For those of you who didn’t (yet) read the previous installment of this series, let me explain quickly the topics it covered. To begin with, I gave an accessible explanation of what the Observer pattern is about, and accompanied all the corresponding theory with a straightforward practical example, to help you easily understand how to apply this popular design pattern in your own PHP 5 applications. I’m don’t mean to say that you’re going to grasp the logic of observer objects in no time, but I firmly believe that a simple example will help you out by pointing you in the right direction.

Provided that you already know what an observer object is, you’ll realize that this pattern is indeed helpful for decoupling disparate objects from the rest of the application. Besides, the pattern will assist you in the development of programming mechanisms aimed at reflecting specific changes produced by several components at the application’s core level. This is a highly desired feature, particularly if you’re building PHP programs that require the implementation of truly independent objects.

Right, I hope the concepts that I touched on above are fresh in your mind now, because it’s time to continue exploring the advantages of using the Observer pattern in PHP 5. Now, surely you’re wondering: how does this story continue? Well, over the course of this last tutorial, I’ll be moving the application of observer objects toward the real world, in this case by showing you how to include these objects within a set of form-validation classes. After reading this article, you should be equipped with a decent knowledge of how a form checking application can use the powerful features of this widely-known design pattern.

Having established the goals for this last installment of the series, it’s time to continue learning about observer objects. Let’s do it together!

{mospagebreak title=Going backward: listing the full source code for the form validation classes}

Prior to any attempt to create a true observer object within the form validation application that you learned in the previous article, it would be very convenient to have close at hand the definition of all the data checking classes that I defined previously. In this way, you’ll understand more easily how the Observer pattern can be properly implemented inside the application in question. Therefore, here’s the complete listing of all the verification classes previously created:

  // define DataValidator class
  class DataValidator{
    protected $method;
    protected $formObserver;
    public function __construct(FormObserver $formObserver){
        $this->formObserver=$formObserver;
        $this->method=$_POST;
    }
    protected function notifyObserver($errorMessage){
        $this->formObserver->addNotification($errorMessage);
    }
  }
  // define StringValidator class
  class StringValidator extends DataValidator{
    public function __construct($formObserver){
        parent::__construct($formObserver);
    }
    // validate strings
    public function validate($field,$errorMessage,$min=4,$max=32)
{
        if(!isset($this->method[$field])||trim($this->method
[$field])==”||strlen($this->method[$field])<$min||strlen($this-
>method[$field])>$max){
            $this->notifyObserver($errorMessage);
        }
    }
  }
  // define IntegerValidator class
  class IntegerValidator extends DataValidator{
    public function __construct($formObserver){
        parent::__construct($formObserver);
    }
    // validate integers
    public function validate($field,$errorMessage){
        if(!isset($this->method[$field])||!is_numeric($this-
>method[$field])||intval($this->method[$field])!=$this->method
[$field]){
            $this->notifyObserver($errorMessage);
        }
    }
  }
  // define NumberValidator class
  class NumberValidator extends DataValidator{
    public function __construct($formObserver){
        parent::__construct($formObserver);
    }
    // validate numbers
    public function validate($field,$errorMessage){
        if(!isset($this->method[$field])||!is_numeric($this-
>method[$field])){
            $this->notifyObserver($errorMessage);
        }
    }
  }
  // define RangeValidator class
  class RangeValidator extends DataValidator{
    public function __construct($formObserver){
        parent::__construct($formObserver);
    }
    // validate ranges
    public function validate($field,$errorMessage,$min=1,$max=99){
        if(!isset($this->method[$field])||$this->method[$field]
<$min||$this->method[$field]>$max){
            $this->notifyObserver($errorMessage);
        }
    }
  }
  // define AlphaValidator class
  class AlphaValidator extends DataValidator{
    public function __construct($formObserver){
        parent::__construct($formObserver);
    }
    // validate alphabetic field
    public function validate($field,$errorMessage){
        if(!isset($this->method[$field])||!preg_match(“/^[a-zA-Z]
+$/”,$this->method[$field])){
            $this->notifyObserver($errorMessage);
        }
    }
  }
  // define AlphanumValidator class
  class AlphanumValidator extends DataValidator{
    public function __construct($formObserver){
        parent::__construct($formObserver);
    }
    // validate alphanumeric data
    public function validate($field,$errorMessage){
        if(!isset($this->method[$field])||!preg_match(“/^[a-zA-
Z0-9]+$/”,$this->method[$field])){
            $this->notifyObserver($errorMessage);
        }
    }
  }
  // define EmailValidator class
  class EmailValidator extends DataValidator{
    public function __construct($formObserver){
        parent::__construct($formObserver);
    }
    // validate email
    public function validate($field,$errorMessage){
        if(!isset($this->method[$field])||!preg_match
(“/.+@.+..+/”,$this->method[$field])||!checkdnsrr(array_pop
(explode(“@”,$this->method[$field])),”MX”)){
            $this->notifyObserver($errorMessage);
        }
    }
  }
  // define EmailValidatorWin class (Windows systems)
  class EmailValidatorWin extends DataValidator{
    public function __construct($formObserver){
        parent::__construct($formObserver);
    }
    public function validate($field,$errorMessage){
        if(!isset($this->method[$field])||!preg_match
(“/.+@.+..+/”,$this->method[$field])||!$this->windnsrr(array_pop
(explode(“@”,$this->method[$field])),”MX”)){
            $this->notifyObserver($errorMessage);
        }
    }
    // private method ‘windnsrr()’ for Windows systems
    private function windnsrr($hostName,$recType=”){
        if(!empty($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;
    }
  }

Here you have them. As you can see above, I listed the complete set of data checking classes that I plan to use with the form validation system, in such a way that they can notify an observer object of any potential errors via the corresponding “notifyObserver()” method. Obviously, this object will determine the best course of action to take, in accordance with the programming logic implemented inside the application.

Since the above data validation classes should be familiar to you (remember that they were originally defined in the second part of this series), it’s time to see how an observer class can be created, in order to decide what tasks to perform, based on the proper notifications sent by the pertinent checking classes.

Due to the important concepts that I’m going to deploy in the upcoming section, I strongly suggest you keep reading, in order learn how to include an observer class within the previous form validation application.

{mospagebreak title=Notifying the application’s core level of validation errors: defining a form observer class}

Once all the data checking classes have been appropriately created, defining a form observer class is indeed a no-brainer process which can be performed quite easily.

To put it simply, the form observer class I’m just about to create will perform the following tasks: first, it will check for all the notifications received from the respective form validation classes, and then it will show either a confirmation message (if the data entered on the form doesn’t contain errors) or redisplay the form in question. In the latter case, the user can correct the information and resubmit it.

Based on the previous explanation, you can understand how the Observer pattern is applied here. First, I have a set of independent classes, where their scope is clearly delimited by the type of data that they have to validate, and second, there is a form observer class which takes all the notices sent by these classes and determines the best action to take. Are you beginning to see how an observer object works in the context of this particular application?

Okay, that’s a bit of theory. Now, take a look at the definition of the “FormObserver” class:

  // class FormObserver
  class FormObserver{
    private $notifications;
    private $formVar;
    public function __construct($formVar){
        $this->formVar=$_POST[$formVar];
        $this->notifications=array();
    }
    public function addNotification($errorMessage){
        $this->notifications[]=$errorMessage;
    }
    public function checkNotifications(){
        if(!$this->formVar){
            $this->displayForm();
        }
        else{
            if(count($this->notifications)>0){
                // form is not OK
                $this->displayErrors();
                $this->displayForm();
            }
            else{
                // form is OK
                echo ‘<p>The form has been submitted
successfully!</p>’;
            }
        }
    }
    // display errors
    private function displayErrors(){
        $errstr=’<p>Please correct the following fields and
resubmit the form:</p>’;
        foreach($this->notifications as $notification){
          $errstr.=’<p>’.$notification.’</p>’;
        }
        echo $errstr;
    }
    // display form
    public function displayForm(){
            $formstr=’<form action=”‘.$_SERVER['PHP_SELF'].’”
method=”post”>’;
            $formstr.=’First Name <input type=”text”
name=”firstname” value=”‘.$_POST['firstname'].’”/><br />’;
            $formstr.=’Last Name <input type=”text”
name=”lastname” value=”‘.$_POST['lastname'].’” /><br />’;
            $formstr.=’Email <input type=”text” name=”email”
value=”‘.$_POST['email'].’” /><br />’;
            $formstr.=’Age <input type=”text” size=”1″ name=”age”
value=”‘.$_POST['age'].’” /><br />’;
            $formstr.=’<input type=”submit” value=”Send”
name=”send” /></form>’;
            echo $formstr;
    }
  }

As you can see, the “FormObserver” class defined above is extremely understandable. Undoubtedly, the most important method worth examining here is “checkNotifications(),” which checks for the existence of error messages submitted by the respective validation classes and decides what course of action should be taken.

If the data entered into the form is correct, then a confirmation message is presented to the user. If any errors were found during the validation process, the form is redisplayed by calling the “displayForm()” method. In this specific example, I decided to use a form composed of only three text fields, but you can modify this condition by coding a new form, or even using a completely independent class for generating all the form elements. Due to the native extensibility of this form observer class, it can be expanded rapidly.

Fine, at this point I hope that you’ve grasped how a form observer class can be created with minor hassles, which leads directly to decoupling the corresponding data validation classes from the rest of the application. At the same time, this class allows you to implement a centralized mechanism for reflecting all the errors that happened when validating the form in question. This is how an observer works, according to the theory you learned in the course of the previous articles.

Having illustrated the corresponding definition for the previous “FormObserver” class, the next step rest on demonstrating how a simple form can be validated by using this class. Regarding this topic, in the next section I’ll set up a simple example, which will teach you how the Observer pattern’s theory can be translated into fully functional code.

Please click on the link below and keep reading to find out how this will be done.

{mospagebreak title=Validating forms: putting the form observer class to work}

Based on the class definitions that you learned over the previous section, below I coded a basic example of how to validate an online form, comprised of the following three text fields: First Name, Last Name and Email. Please take a look at the following code snippet:

  try{
    // instantiate ‘FormObserver’ object
    $formObs=new FormObserver(‘send’);
    // instantiate validators and validate fields
    $alphaVal=new AlphaValidator($formObs);
    $alphaVal->validate(‘firstname’,'Enter a valid First Name
(only alphabetic characters).’);
    $alphaVal->validate(‘lastname’,'Enter a valid Last Name (only
alphabetic characters).’);
    $intVal=new IntegerValidator($formObs);
    $intVal->validate(‘age’,'Enter a valid age (0-99).’);
    $emailVal=new EmailValidatorWin($formObs);
    $emailVal->validate(‘email’,'Enter a valid email address.’);
    // check for errors
    $formObs->checkNotifications();
  }
  catch(Exception $e){
            echo $e->getMessage();
            exit();
  }

That’s all you need to get the form validation application working. As you can appreciate, first I instantiated a “FormObserver” object, which is naturally passed to each of the data checking classes that will be used during the verification process. Then the form observer checks for any eventual raised errors and either displays a confirmation message (if the data entered on the form is considered valid input), or redisplays the form in question.

To simplify the above explanation even more, here’s a screen shot that illustrates how the form validation application works:

Definitely, you’ll have to agree with me that the Observer pattern has been quite helpful for constructing an extensible form validation mechanism. Although you may have tried other approaches in the past, this one certainly deserves a closer look, since it shows in a clear way how to apply this design pattern in a real world situation. Give it a try!

Final thoughts

Our journey covering the Observer pattern has now finished. From covering the key concepts, to working with real world examples, I hope that you learned all the topics required to get you off to a good start using this popular pattern. As with other design patterns, practice is the best way to master this one, therefore I strongly encourage you to begin using it (when applicable) inside your own Web applications.

Once you master its fundamentals, fun is guaranteed. See you in the next PHP tutorial!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan