PHP
  Home arrow PHP arrow Page 3 - Centralizing the Validation of Data with the Observer Pattern in PHP
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? 
PHP

Centralizing the Validation of Data with the Observer Pattern in PHP
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 8
    2006-07-31


    Table of Contents:
  • Centralizing the Validation of Data with the Observer Pattern in PHP
  • Going backward: listing the full source code for the form validation classes
  • Notifying the application's core level of validation errors: defining a form observer class
  • Validating forms: putting the form observer class to work

  • 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


    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
    ( Page 3 of 4 )

    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
     

       

    PHP ARTICLES

    - 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
    - Method Chaining: Adding More Methods to the ...
    - Method Chaining in PHP 5
    - The Role of Interfaces in Applying the Depen...
    - Dependency Injection: Using a Setter Method ...
    - Using a Model Class with the Dependency Inje...
    - Injecting Objects Using Setter Methods with ...
    - Injecting Objects by Constructor with the De...
    - The Dependency Injection Design Pattern in P...
    - Performing Inferential Statistical Analysis ...
    - Performing Descriptive Statistical Analysis ...





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