Home arrow PHP arrow Page 3 - Centralizing the Validation of Data with the Observer Pattern in PHP

Notifying the application's core level of validation errors: defining a form observer class - 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.

TABLE OF CONTENTS:
  1. Centralizing the Validation of Data with the Observer Pattern in PHP
  2. Going backward: listing the full source code for the form validation classes
  3. Notifying the application's core level of validation errors: defining a form observer class
  4. Validating forms: putting the form observer class to work
By: Alejandro Gervasio
Rating: starstarstarstarstar / 8
July 31, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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.



 
 
>>> 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: