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!
blog comments powered by Disqus |
|
|
|
|
|
|
|