Creating a Validation Helper Class

Helper classes seem easy to build — almost deceptively so. If you’re building a helper class to assist with a crucial function, however, such as validation, the approach you need to take may seem a bit less straightforward. This fifth article in an eight-part series on building helper classes walks you through the process, complete with hands-on examples.

True to form, for any PHP developer with only an average background in the object-oriented paradigm, building helper classes should be a pretty straightforward task. After all, this process doesn’t demand the effort required for creating a full-blown library.

It’s fair to say, though, that even when a helper is designed to perform certain tasks that at least in theory shouldn’t be extremely complex, in practice things can get a bit intimidating. The reason for this is simple: there are times when a helper class needs to implement methods or functions that play a role as crucial as a much larger module or plug-in.

Of course, speaking in practical terms, categorizing a particular class as a helper or as a core library depends strongly on the context in which it will be used. But regardless of its rather intangible nature, helpers are undeniably a fundamental part of a PHP developer’s toolbox.

Therefore, if you’re interested in arming yourself with the right tools to start building your own helper classes in PHP 5 with minor efforts, then don’t hesitate any longer; begin reading this series of articles right away!

Before you skip over this introduction, however, it would be helpful to recall that I left off the previous article discussing how to create a URL helper class whose main functionality was implemented around the $_SERVER PHP superblobal array. Despite the simplicity of many of its methods, the class demonstrated how to utilize it without having to deal with any instances of it, since the methods were declared static, and therefore used out of the object context.

Nonetheless, this journey through the ins and outs of building helper classes with PHP 5 hasn’t finished yet. In this fifth part of the series I plan to build a class that will be responsible for validating input data, either supplied by users or from a different source.

In this specific project, this validation helper will make use of the PHP filter extension to perform the pertinent checking processes, but it can be easily adapted to use custom methods as well.

Now, it’s time to leave the theory behind us and start learning how to create a helper class to validate input data. Let’s go!

{mospagebreak title=Review: a URL-handling helper class}

Just in case you haven’t read the previous part of the series, where I explained how to build a simple URL-handling helper class, below I included the full source code for this class, along with some examples of how to use it to retrieve some of the values stored in the $_SERVER PHP array.

That being said, here’s the signature of the URL helper class:

class URLHelper

{

// constructor not implemented

public function __construct(){}

 

// get web server root

public static function get_document_root()

 {

return $_SERVER['DOCUMENT_ROOT'];

}

 

// get script URL

public static function get_script_url()

{

return $_SERVER['PHP_SELF'];

}

 

// get script query string

public static function get_query_string()

{

return $_SERVER['QUERY_STRING'];

}

 

// get request URI

public static function get_request_uri()

{

return $_SERVER['REQUEST_URI'];

}

 

// get script file name

public static function get_script_filename()

{

return $_SERVER['SCRIPT_FILENAME'];

}

 

// get request method

public static function get_request_method()

{

return strtolower($_SERVER['REQUEST_METHOD']);

}

 

}

Undeniably, the definition of the above “URLHelper” class is pretty easy to follow. It’s comprised of a few basic static methods, which behave like simple proxies for the aforementioned $_SERVER PHP array.

That was the boring part. However, the following code samples should be a bit more interesting for you; they show how to use the helper class to generate some dynamic URLs. Here they are:

echo URLHelper::get_document_root();

/*

// displays the following

C:/Program Files/Apache Group/Apache2/htdocs

*/

 

echo URLHelper::get_request_method();

/*

displays the following

get

*/

 

echo URLHelper::get_query_string();

/*

displays the following

fname=Alejandro&lname=Gervasio

*/

 

echo URLHelper::get_request_uri();

/*

displays the following

/helpers/helper_example.php

*/

 

echo URLHelper::get_script_filename();

/*

displays the following

C:/Program Files/Apache Group/Apache2/htdocs/helpers/helper_example.php

*/

 

echo URLHelper::get_script_url();

/* displays the following

/helpers/helper_example.php

*/

From the previous examples, it’s clear to see that the methods of the URL helper class can be easily improved, or even better, it’s possible to add new ones that perform more useful tasks, such as generating breadcrumbs for a web page and calculating the base path of a given web site.

Despite the lack of these features, this sample helper class should give you a clear idea of how to take advantage of its functionality without having to spawn an instance of it.

Well, at this point you’ve surely recalled how to work with the previous URL helper, so the next thing that I’m going to do will consist of building a brand new class. This class will be responsible for validating common data, such as float and integer numbers, IP and email addresses, and so forth.

If you want to learn in depth how this new helper class will be developed, you’ll have to click on the link that appears below and read the following section.

{mospagebreak title=Creating a validation class}

You, as a PHP developer, know that one of the most common and crucial tasks that a PHP application must perform is validating data, generally coming from users or visitors of a web site. In object-based programs, this process is usually delegated to a full-blown validation library, but there are cases where it’s also possible to combine the functionality of a library like this with the capability provided by a simpler helper.

In this particular case, I’m going to demonstrate how to build a basic helper class that will validate inputted data, without boasting the complexity of a fully-loaded library.

Now that I have clarified that point, please take a look at the initial definition of this validation helper class, which looks like this:

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);

}

}

As shown above, the whole new validation helper class is comprised of only a couple of methods, apart from the constructor, for validating integers and float numbers respectively.

Also, it’s worthwhile to notice that the pertinent validation tasks are accomplished by using the PHP filter extension. This makes for a truly no-brainer process, but it’s also possible to replace the filters with custom methods that perform the same validation processes.

So far, everything looks pretty good. At this stage I’ve developed a validation helper class that verifies integers and float numbers. While this can be pretty useful as a starting point, it’s possible to aggregate more functionality to the helper class by coding other methods that validate other data types.

Based on that premise, in the last section of this tutorial I’m going to add a pair of additional methods to the helper class, which will be charged with validating alphabetic and alphanumeric values.

To see how these methods will be defined, go ahead and read the following segment. It’s only one click away.

{mospagebreak title=Validating alphabetic and alphanumeric values}

As I expressed in the section that you just read, I’m going to finish this installment of the series by adding two more methods to the “ValidatorHelper” class, which will be responsible for checking alphabetic and alphanumeric data.

So, in summary, the methods that will perform these tasks look like this:

// 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]+$/")));

}

Again, I used the “filter_var()” function that comes with the PHP filter extension to give a concrete implementation to the two previous methods. In the first case, the method will validate alphabetic values, while in the second case, the other method will verify alphanumeric values. That was pretty simple to grasp, wasn’t it?

Well, now that you know how these two brand new methods work, it’s time to list the source code of the validation helper class, whose functionality has been extended a bit further. So, here’s how the class looks:

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]+$/")));

}

}

There you have it. I don’t want to market the helper class to you, but admittedly it has become a more functional piece of code. Of course, there’s plenty of room to add more methods to the class if you need to validate other common data, such as IP and email addresses, strings and so forth. However, all of these features will be incorporated in the upcoming tutorial of the series.

For the moment, I encourage you to introduce your own enhancements to the previous helper class. In this way you will not only sharpen your existing programming skills, but get a more intimate knowledge of using the PHP filters extension.

Final Thoughts

In this fifth part of the series, I discussed the creation of a validation helper class in PHP 5, which was given the capability to check integers and float numbers, and alphabetic and alphanumeric values as well.

But, as you may have realized, it’s pretty easy to extend the capabilities of the class via PHP filters and add methods to it that check for email and IP addresses, strings, etc.

That will be exactly the topics that I plan to cover in the next tutorial, so you don’t have any excuses to miss it!

Google+ Comments

Google+ Comments