Validating Incoming Data by Using Polymorphism with Objects in PHP 5

If you’re a PHP developer who wants to learn how to take advantage of polymorphism to build more efficient and robust object-oriented applications, then this group of articles might be what you need. Welcome to the final part of the series that started with "Using Polymorphism with Objects in PHP 5." Comprised of three tutorials, this series shows you how to create polymorphic classes with PHP; it also teaches you how to use them in real-world situations.

Introduction

Having already introduced the subject of this series of articles, let me step back quickly to the second tutorial to refresh your memory of the topics it covered. As you’ll certainly recall, I demonstrated how one of the main pillars of object-oriented programming, that is polymorphism, can be used to generate dynamic web pages with minor hassles.

As you learned in that article, building basic web documents by using the functionality provided by a few polymorphic classes can be very useful, since this approach allows you to declare, for instance, one method that is shared by different sub classes, and define programmatically what kind of operations should be performed by the method in question.

In essence, the previous schema illustrates in a nutshell how polymorphism works, since this model demonstrates how different objects that belong to the same family can behave differently using an identical method. Of course, this capacity was applied to building dynamic web pages, but it can also be used in other cases, such as developing database abstraction classes, generating online forms, and so forth.

Speaking of the numerous situations where Polymorphism can be implemented successfully to build more efficient object-based programs, in this final installment of the series I’m going to show you how to develop an expandable PHP mechanism for validating different types of incoming data. This will demonstrate how this important pillar of object-oriented programming can be used with a plethora of applications.

So are you ready to learn how to use polymorphism for checking user-provided data? Okay, let’s get started!

{mospagebreak title=Using polymorphism to validate input data}

A good place to start demonstrating how a group of polymorphic classes can be used to validate user-supplied data is with building a base abstract class. This class will define only one generic method, in this case called "validate()," and aimed at validating different types of input data.

After defining this parent class, I’ll derive a few concrete subclasses which will implement concretely the aforementioned "validate()" method, so each of them can be used to validate specific types of incoming data. Now, do you see how polymorphism fits into this schema? I’m sure you do!

All right, now that I have explained how I plan to create a data validation application using some polymorphic classes, please take a look at the signature of the corresponding parent, which as I said before, has been declared abstract. Its short definition is as follows:

// define ‘DataValidator’ class
abstract class DataValidator{
   abstract public function validate($inputData);
}

As you can see, the above "DataValidator" class acts simply as an interface for creating all the corresponding subclasses that will be responsible for validating specific types of incoming data. In this case in particular, notice that the class only exposes an abstract "validate()" method, but this should give you at least a vague idea of how the classes that will created later on will implement concretely the method in question.

Okay, now that you know how the base class looks, it’s time to start deriving some concrete classes from it so they’re able to validate different types of user-supplied data.

Having said that, here are the definitions that correspond to the first four subclasses. They are tasked with checking empty strings first, then integers and numeric data, and finally ranges of values.

The respective signatures for these brand new classes are as follows:

// define ‘EmptyValidator’ class
class EmptyValidator extends DataValidator{
  
const MIN=4;
  
const MAX=32;
  
public function validate($inputData){
    
if(!$inputData||trim($inputData)==”||strlen($inputData)
<self::MIN||strlen($inputData)>self::MAX){
      
return false;
    
}
    
return true;
   }
}

// define ‘IntegerValidator’ class
class IntegerValidator extends DataValidator{
  
public function validate($inputData){
    
if(!$inputData||!is_numeric($inputData)||intval
($inputData)!=$inputData){
      
return false;
    
}
    
return true;
  
}
}

// define ‘NumericValidator’ class
class NumericValidator extends DataValidator{
  
public function validate($inputData){
    
if(!$inputData||!is_numeric($inputData)){
      
return false;
    
}
    
return true;
  
}
}

// define ‘RangeValidator’ class
class RangeValidator extends DataValidator{
  
const MIN=1;
  
const MAX=99;
  
public function validate($inputData){
    
if(!$inputData||$inputData<self::MIN||$inputData>self::MAX){
      
return false;
    
}
    
return true;
  
}
}

As shown above, the data validating classes listed previously are an excellent example of how to use the functionality provided by polymorphism to check a broad range of incoming data. This concept becomes clear since all the prior classes belong to the same "DataValidator" family, but in each case they implement the "validate()" method in a different way. Pretty good, isn’t it?

Okay, at this point I’m positive that you already grasped the logic that stands behind this "polymorphic" data validation system, so it’s time to move forward and continue defining some additional subclasses. In this way the initial capacity of the system in question can be greatly expanded.

To see how these brand new data checking classes will be built, please click on the link shown below and keep reading.

{mospagebreak title=Extending the implementation of polymorphism}

As I stated in the section that you just read, below I included a new group of data checking classes, created specifically for validating alphabetic and alphanumeric values, as well as email addresses. You should notice that I also created an additional class that verifies the validity of a given email address that can be used with Windows-based machines, in case you’re working with that operating system.

Having clarified that, here are the signatures that correspond to the aforementioned classes. They look like this:

// define ‘AlphabeticValidator class
class AlphabeticValidator extends DataValidator{
   public function validate($inputData){
    
if(!$inputData||!preg_match("/^[a-zA-Z]+$/",$inputData)){
      
return false;
    
}
    
return true;
  
}
}

// define ‘AlphanumericValidator’ class
class AlphanumericValidator extends DataValidator{
  
public function validate($inputData){
    
if(!$inputData||!preg_match("/^[a-zA-Z0-9]+$/",$inputData)){
      
return false;
    
}
    
return true;
  
}
}

// define ‘EmailValidator’ class
class EmailValidator extends DataValidator{
  
public function validate($inputData){
    
if(!$inputData||!preg_match("/.+@.+..+./",$inputData)||!
checkdnsrr(array_pop(explode("@",$inputData)),"MX")){
      
return false;
    
}
    
return true;
   
}
}

// define ‘EmailValidatorWin’ class
class EmailValidatorWin extends DataValidator{
  
public function validate($inputData){
    
if(!$inputData||!preg_match("/.+@.+..+./",$inputData)||!
$this->windnsrr(array_pop(explode("@",$inputData)),"MX")){
      
return false;
    
}
    
return true;
  
}
  
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 you can see, the above data validation classes look very similar to the ones created in the previous section. Logically, the only difference to spot here is with reference to the diverse implementations of the respective "validate()" method. It’s different for each class.

Again, you’ll realize that I’m playing with the concept of polymorphism to expand the capacity of this data checking application, something that you can try for yourself if you want to verify additional types of data. As you learned previously, the process is indeed simple.

Well, at this stage I have built a decent number of data checking classes for validating a broad range of user-supplied entries by taking advantage of polymorphism. However, there’s still a missing piece in this schema, since a programmatic mechanism is required here to demonstrate more clearly how to use the polymorphic facet exposed by all these classes.

So, what is that piece? In short, I plan to use a factory class so I can easily spawn a certain number of validating objects. These objects will be used to check different types of user-supplied data. Of course, I’ll keep the source code of this factory class extremely simple, because I don’t want to bother you with irrelevant details. Here’s how this class looks:

// define ‘ValidatorFactory’ class
class ValidatorFactory{
  
public function createValidator($validator){
    
return new $validator();
   
}
}

The above factory class returns to client code a specific kind of validating object, in accordance with the incoming $validator parameter passed to its respective "createValidator()" method.

So far, so good. At this point, I have shown you the complete signatures that correspond to all the validation classes that you learned before, in conjunction with an additional factory class. Therefore, the next step will consist of developing a hands-on example, where you’ll see how all these classes can be put to work together.

Want to see how this practical example will be developed? Keep reading, please.

{mospagebreak title=Validating user-supplied data by using polymorphic objects}

In accordance with the concepts that I deployed in the previous section, here is an illustrative example that shows how to use some of the data checking classes that you learned before. This will demonstrate how useful and powerful polymorphism can be.

Take a look at the following code sample, please:

try{
 
$valFactory=new ValidatorFactory();
 
// create ‘EmptyValidator’ object
 
$emptyVal=$valFactory->createValidator(‘EmptyValidator’);
 
if($emptyVal->validate(”)){
   
echo ‘Input data is valid!';
 
}
 
else{
   
echo ‘Input data is not valid!';
 
}
 
// create ‘IntegerValidator’ object
 
$integerVal=$valFactory->createValidator(‘IntegerValidator’);
 
if($integerVal->validate(1000)){
   
echo ‘Input data is valid!';
 
}
 
else{
   
echo ‘Input data is not valid!';
 
}
 
// create ‘NumericValidator’ object
 
$numericVal=$valFactory->createValidator(‘NumericValidator’);
 
if($numericVal->validate(‘ABCD’)){
   
echo ‘Input data is valid!';
 
}
 
else{
   
echo ‘Input data is not valid!';
 
}
 
// create ‘AlphanumericValidator’ object
 
$alphanumericVal=$valFactory->createValidator
(‘AlphanumericValidator’);
 
if($alphanumericVal->validate(‘ABCD123456′)){
   
echo ‘Input data is valid!';
 
}
 
else{
   
echo ‘Input data is not valid!';
 
}
 
// create ‘AlphabeticValidator’ object
 
$alphabeticVal=$valFactory->createValidator
(‘AlphabeticValidator’);
 
if($alphabeticVal->validate(‘ABCD’)){
   
echo ‘Input data is valid!';
 
}
 
else{
   
echo ‘Input data is not valid!';
 
}
}
catch(Exception $e){
 
echo $e->getMessage();
 
exit();
}

As you can see, the sample script shown above demonstrates in a friendly fashion how to use some of the classes created previously to validate different types of data. The respective objects display a primitive message indicating whether or not a particular value is valid, but this can be easily changed to fit your personal needs.

As usual, feel free to tweak the source code of all the classes shown in this article, so you can eventually acquire a better understanding of how polymorphism can be used to build more efficient PHP applications.

Final thoughts

Finally, we’ve come to the end of this series. Hopefully, after reading these three tutorials, you’ll have a more accurate idea of how to take advantage of the functionality provided by polymorphism to build more solid and robust object-based PHP applications.

As expressed earlier, polymorphism can be applied successfully in those situations where you need to work with a bunch of objects that belong to the same family, but eventually can have different behaviors.

See you in the next PHP tutorial!

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