If you’re anything like me, at this stage you want to see how to implement a concrete validation strategy, right? Well, considering that most of the functionality has already been encapsulated inside the previous “AbstractValidator,” building a strategy class that checks to see whether or not an inputted value is an integer is as simple as deriving the following concrete validator: (IntegerValidator.php) <?php class IntegerValidator extends AbstractValidator { protected $_filter = FILTER_VALIDATE_INT; protected $_errorMessage = 'Please enter an integer value.'; } There you have it. Didn’t I tell you from the very beginning that the implementation of the Strategy pattern in PHP was a fairly straightforward process? Well, the definition of the above “IntegerValidator” class shows this in a nutshell. It simply overrides the $_filter and $_errorMessage properties defined by its parent, which automatically provides it with the ability to validate integer numbers. If you wish to test the above class as a standalone component, the task would be similar to coding the following script: $intValidator = new IntegerValidator('abcde'); if (!$intValidator->validate()) { echo $intValidator->getFormattedError(); /* displays the following The value abcde is incorrect. Please enter an integer value. */ } else { 'The data is correct!'; } As you can see, the “IntegerValidator” class is flexible enough to be used either as an isolated piece or as a companion strategy that can be injected inside another class. Obviously, the latter is the approach that I’m going to discuss in this case, but the earlier example should give you a good idea of how to create and use different validators based on the functionality encapsulated within their abstract parent. Final thoughts In this second part of the series, I went one step further in the implementation of the Strategy design pattern in PHP. I proceeded to create a loosely-coupled class, which was charged with validating integer numbers. This validator (if the name is really applicable) is the first of a list of strategies classes that I plan to define in upcoming parts of the series. Having already defined a class capable of checking integers, the next step that I’m going to take will consist of creating another strategy class. This time it will be responsible for validating float numbers. Do you want to learn the full details of this process? Then don’t miss the following tutorial!
blog comments powered by Disqus |
|
|
|
|
|
|
|