HomePHP Using Static Methods to Validate Data with Helpers in PHP 5
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!