As I said, it’s feasible to build a modular and flexible data validation application by taking advantage of the functionality offered by the Strategy pattern. To do so, I'll start by defining a simple web form helper. It will take as an input argument a validator object (the strategy), whose originating class will be shown in upcoming articles of this series. For the moment, however, focus your attention on the definition of the helper, which looks like this: (FormHelper.php) <?php class FormHelper { protected $_validators = array(); protected $_errors = array();
// add a validator public function addValidator(AbstractValidator $validator) { $this->_validators[] = $validator; return $this; }
// get all the validators public function getValidators() { return !empty($this->_validators) ? $this->_validators : null; }
// validate inputted data public function validate() { $validators = $this->getValidators(); if (null !== $validators) { foreach ($validators as $validator) { if (!$validator->validate()) { $this->_errors[] = $validator->getFormattedError(); } } } return empty($this->_errors) ? true : false; } } As you can see, the above “FormHelper” class implements for now three concrete methods. The first one, called “addValidator(),” permits you to inject a set of independent validation objects, which are stored on the protected $_validators” property. This method is actually the “heart and soul” of the Strategy pattern, as it uses the power of Composition to inject a predefined validation strategy inside the helper class. On the other hand, the “validate()” method first iterates over all the inputted validator objects, uses them to check if the supplied data is valid, and finally stores the corresponding error messages by calling the “getFormattedError()” method defined by the objects in question. Naturally, you’ll understand the implementation of this method better when I show you the definition of each validation class, but keep in mind that this is a work in progress, so for the moment keep your attention focused on how the helper class does its thing. Even though at this point the helper class looks pretty skeletal, it’s clear to see that it can use a specific strategy, that is one or multiple validator objects, to check incoming data. Now, are you starting to see how useful the Strategy pattern can be when building flexible applications? I guess you do! However, in its current state the helper still isn’t capable of retrieving and removing the error messages stored during the entire validation process. Fortunately, this can be solved by adding a couple of additional methods to it. Their definitions will be shown in the next section. Now, to see how these extra methods will be defined, click on the link below and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|