Using Static Methods to Validate Data with Helpers in PHP 5

Welcome to the conclusion of an eight-part series on building helpers in PHP 5. It’s been a long journey, modifying our helper class to make it do what we want it to. Finally, in this last part, we’ll put the finishing touches on our validation class so that it functions properly, without the need to spawn helper objects.

For many PHP developers taking the first steps in the fascinating terrain of object-based programming, building helper classes is a mysterious process. That’s easy to understand, considering the thin line of differentiation that sometimes exists between helpers and full-featured libraries.  

Despite this initial intimidating feeling, the truth is that creating helper classes is very often much easier to accomplish than one might think. In most cases the process doesn’t differ too much from developing a regular PHP class.

However, it’s also fair to say that generally methods of a helper class should be declared static, to avoid an eventual instantiation of the class itself. This makes sense, because in a typical situation it’s not necessary to spawn helper objects at all. Instead, the functionality of a helper class is exploited through direct calls to its methods, but always out of the object scope.

Of course, this is only a brief piece of theory behind building helper classes with PHP, which must be properly backed up with some practical examples that demonstrate this process. And that has been the goal of this series of articles, including the previous one, where I discussed how to use a basic helper class to validate different types of data. The data validated in that article ranged from integer and float numbers, to IP and email addresses as well.

In addition, as you’ll possibly recall, this sample helper had a serious drawback that contradicts the theoretical concepts deployed above. What was wrong with it? The methods of the helper were always called in the object scope, implying that there was a previous instantiation of the class. In this particular case, this process is completely unnecessary, aside from encouraging a bad programming habit.

Therefore, in this last tutorial of the series I’m going to improve the source code of this validation helper class by declaring all of its implemented methods static. After doing that, I’m going to set up some examples that will show how to validate incoming data via these static methods.

So, are you ready to tackle the final chapter of this hopefully educational journey on building helper classes in PHP 5? Then, start reading right now!

{mospagebreak title=Review: checking incoming data with class methods}

Before I proceed to modify the pertinent declarations of the methods that comprise the validation helper class, it’d be helpful to reintroduce its complete source code. In this way you can recall how it was defined originally.

Here’s the entire signature of the helper. Pay close attention to it, please:

class ValidatorHelper

{

// constructor not implemented

public function __construct(){}

 

// validate integer

public function validate_int($value, $min, $max)

{

return filter_var($value, FILTER_VALIDATE_INT, array(‘options’ => array(‘min_range’ => $min, ‘max_range’ => $max)));

}

 

// validate float number

public function validate_float($value)

{

return filter_var($value, FILTER_VALIDATE_FLOAT);

}

 

// validate alphabetic value

public function validate_alpha($value)

{

return filter_var($value, FILTER_VALIDATE_REGEXP, array(‘options’ => array(‘regexp’ => "/^[a-zA-Z]+$/")));

}

 

// validate alphanumeric value

public function validate_alphanum($value)

{

return filter_var($value, FILTER_VALIDATE_REGEXP, array(‘options’ => array(‘regexp’ => "/^[a-zA-Z0-9]+$/")));

}

 

// validate URL

public function validate_url($url)

{

return filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED);

}

 

// validate IP address

public function validate_ip($ip)

{

return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);

}

 

// validate email address

public function validate_email($email)

{

return filter_var($email, FILTER_VALIDATE_EMAIL);

}

}

In the previous part of the series I offered a detailed explanation of how the above helper class was built, so I’m not going to waste your time discussing this topic here. Instead, I’m going to list the examples developed in that tutorial that show how to use it to validate different arguments.

Here are the pertinent examples. Again, take a close look at them:

$validator = new ValidatorHelper();

 

// example on validating an integer value

if ($validator->validate_int(10.2, 1, 100) === FALSE)

{

echo ‘Input value is not a valid integer.’;

}

else

{

echo ‘Input value is a valid integer.’;

}

/*

displays the following

Input value is not a valid integer.

*/

 

// example on validating a float value

if ($validator->validate_float(1234.5) === FALSE)

{

echo ‘Input value is not a valid float number.’;

}

else

{

echo ‘Input value is a valid float number.’;

}

/*

displays the following

Input value is a valid float number.

*/

 

// example on validating an alphabetic value

if ($validator->validate_alpha(‘a1234′) === FALSE)

{

echo ‘Input value is not a valid alphabetic value.’;

}

else

{

echo ‘Input value is a valid alphabetic value.’;

}

/*

displays the following

Input value is not a valid alphabetic value.

*/

 

// example on validating an alphanumeric value

if ($validator->validate_alphanum(‘a1234′) === FALSE)

{

echo ‘Input value is not a valid alphanumeric value.’;

}

else

{

echo ‘Input value is a valid alphanumeric value.’;

}

/*

displays the following

Input value is a valid alphanumeric value.

*/

 

// example on validating a URL

if ($validator->validate_url(‘http://devshed.com’) === FALSE)

{

echo ‘Input value is not a valid URL.’;

}

else

{

echo ‘Input value is a valid URL.’;

}

/*

displays the following

Input value is a valid URL.

*/

 

// example on validating an IP address

if ($validator->validate_ip(’127.0.0.1′) === FALSE)

{

echo ‘Input value is not a valid IP address.’;

}

else

{

echo ‘Input value is a valid IP address.’;

}

/*

displays the following

Input value is a valid IP address

*/

 

// example on validate an email address

if ($validator->validate_email(‘info@domain.com’) === FALSE)

{

echo ‘Input value is not a valid email address.’;

}

else

{

echo ‘Input value is a valid email address.’;

}

/*

displays the following

Input value is a valid email address

*/

Undoubtedly, understanding how to use the “ValidatorHelper” class to verify IP and email addresses, alphabetic and alphanumeric values, and so forth is indeed a straightforward process that should be easy for you to tackle.

Nevertheless, apart from studying the way that each validation process is properly performed, I’d like you to pay attention to the issue that I mentioned in the introduction, which certainly makes an inappropriate use of the helper.

Yes, you guessed right! In all the cases the methods of the class have been called in the object scope, which is completely unnecessary for the reasons that I gave at the beginning of the article.

So, to solve this issue quickly and elegantly, in the following segment I’m going to modify the definitions of the pertinent methods by declaring them static. It’ll be that simple, really.

To learn the full details of this process, click on the link below and read the section to come.

{mospagebreak title=Declaring the class’s methods to be static}

In order to prevent an incidental instantiation of the validation helper class, I’m going to redefine all of its methods, turning them into static ones.

This process is depicted in the following code sample. Have a look at it:

class ValidatorHelper

{

// constructor not implemented

public function __construct(){}

 

// validate integer

public static function validate_int($value, $min, $max)

{

return filter_var($value, FILTER_VALIDATE_INT, array(‘options’ => array(‘min_range’ => $min, ‘max_range’ => $max)));

}

 

// validate float number

public static function validate_float($value)

{

return filter_var($value, FILTER_VALIDATE_FLOAT);

}

 

// validate alphabetic value

public static function validate_alpha($value)

{

return filter_var($value, FILTER_VALIDATE_REGEXP, array(‘options’ => array(‘regexp’ => "/^[a-zA-Z]+$/")));

}

 

// validate alphanumeric value

public static function validate_alphanum($value)

{

return filter_var($value, FILTER_VALIDATE_REGEXP, array(‘options’ => array(‘regexp’ => "/^[a-zA-Z0-9]+$/")));

}

 

// validate URL

public static function validate_url($url)

{

return filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED);

}

 

// validate IP address

public static function validate_ip($ip)

{

return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);

}

 

// validate email address

public static function validate_email($email)

{

return filter_var($email, FILTER_VALIDATE_EMAIL);

}

}

Certainly, at first sight the signature of the above helper class seems to be nearly the same as before, but if you look closely, you’ll realize that all of its methods now have been declared static, which will throw an error if any of them are called in the object context.

What are the benefits in doing this? With a class defined like this, it’s possible to take advantage of its whole functionality while completely preventing its unnecessary instantiation.

Now that the class has been modified for better use, it’s time to see how it can be used for validating incoming data. In the last section of this tutorial I’m going to rewrite the set of examples that you learned before, this time using the class’s static methods.

Read the new few lines. We’re almost done here!

{mospagebreak title=Examples: validating input data with static methods}

If you’re like me, then you wish to learn how to use the helper class, after having modified the declarations of its methods. Therefor, below I rewrote the examples shown in a previous section of this tutorial, which show how to validate different kinds of data by calling the methods in question statically. Here they are:

// validate an integer value

if (ValidatorHelper::validate_int(10.2, 1, 100) === FALSE)

{

echo ‘Input value is not a valid integer.’;

}

else

{

echo ‘Input value is a valid integer.’;

}

/*

displays the following

Input value is not a valid integer.

*/

 

// validate a float value

if (ValidatorHelper::validate_float(1234.5) === FALSE)

{

echo ‘Input value is not a valid float number.’;

}

else

{

echo ‘Input value is a valid float number.’;

}

/*

displays the following

Input value is a valid float number.

*/

 

// validate an alphabetic value

if (ValidatorHelper::validate_alpha(‘a1234′) === FALSE)

{

echo ‘Input value is not a valid alphabetic value.’;

}

else

{

echo ‘Input value is a valid alphabetic value.’;

}

/*

displays the following

Input value is not a valid alphabetic value.

*/

 

// validate an alphanumeric value

if (ValidatorHelper::validate_alphanum(‘a1234′) === FALSE)

{

echo ‘Input value is not a valid alphanumeric value.’;

}

else

{

echo ‘Input value is a valid alphanumeric value.’;

}

/*

displays the following

Input value is a valid alphanumeric value.

*/

 

// validate a URL

if (ValidatorHelper::validate_url(‘http://devshed.com’) === FALSE)

{

echo ‘Input value is not a valid URL.’;

}

else

{

echo ‘Input value is a valid URL.’;

}

/*

displays the following

Input value is a valid URL.

*/

 

// validate an IP address

if (ValidatorHelper::validate_ip(’127.0.0.1′) === FALSE)

{

echo ‘Input value is not a valid IP address.’;

}

else

{

echo ‘Input value is a valid IP address.’;

}

/*

displays the following

Input value is a valid IP address

*/

 

// validate an email address

if (ValidatorHelper::validate_email(‘info@domain.com’) === FALSE)

{

echo ‘Input value is not a valid email address.’;

}

else

{

echo ‘Input value is a valid email address.’;

}

/*

displays the following

Input value is a valid email address.

*/

There you have it. Now the use of the methods that comprise the helper class looks much better, right? Admittedly, the development of this sample class isn’t going to change the way that you currently build your PHP applications, but hopefully it’ll help you grasp more easily the logic that surrounds the correct creation and usage of helpers.

Finally, feel free to edit all of the code examples included in this article, which surely will contribute to sharpening your existing skills in working with static class methods and PHP filters.

Final thoughts

Sadly, we’ve come to the end of this series. I hope you enjoyed reading it as much as I did writing it. But most importantly, I believe that overall the experience has been instructive, since I provided you with an extensive explanation of how to correctly build helper classes in PHP 5.

From this point on, you can use some of the approaches shown in the series and develop your own helper classes, which will save you from the annoyance of writing the same code over and over again.

See you in the next PHP tutorial!

Google+ Comments

Google+ Comments