HomePHP Page 3 - Verifying Float Values with the Strategy Design Pattern
Adding a strategy class for checking float numbers - PHP
In this third part of a series on validating incoming data with the strategy design pattern, I create a brand new strategy class that can check whether or not a supplied input value is a float number. The addition of this class extends the capabilities of the sample validation program that I’m building in this series.
In reality, building a strategy class that can validate float numbers is nearly identical to creating one that checks integers, which we already did in the previous segment. Nonetheless, the best way to prove the truth of my claim is by means of some functional code, so below I included the definition of this brand new strategy class. It looks like this:
class FloatValidator extends AbstractValidator
protected $_filter = FILTER_VALIDATE_FLOAT;
protected $_errorMessage = 'Please enter a float value.';
There you have it. As you can see, building a refined class that validates float numbers is reduced (again) to overriding the already familiar “$_filter” and “$_errorMessage” properties defined by the parent abstract validation class. Of course, “FloatValidator” is as flexible as its partner “IntegerValidator,” so it can be used in conjunction with other classes or in an isolated fashion.
The latter option deserves at least a quick look. So in the last section of this tutorial I’m going to set up a basic script that will show how to use the previous “FloatValidator” class in an independent manner.