As I said in the introduction, in the previous part of the series I defined a basic form helper class for accepting different strategy objects from the outside via its “addValidator()” method. Just in case you still haven’t seen the definition of this helper, below I reintroduced its source code, so you can analyze it and understand its driving logic. Here it is: (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; }
// get validation errors as an array public function getErrors() { return $this->_errors; }
// get validation errors as a string public function getErrorString() { $errors = $this->getErrors(); return !empty($errors) ? implode('', $errors) : ''; }
// clear state of the form helper public function clear() { $this->_validators = array(); $this->_errors = array(); } } Even though the form helper class defines only a few simple methods, the implementations of “addValidator()” and “validate()” are clear enough to demonstrate the logic behind the Strategy pattern. As you can see, instead of being one helper tasked with validating the supplied data, this responsibility has been delegated to the injected validator objects. This permits us to win a battle in two fronts: first, Composition is widely favored over Inheritance, and second, each validation process has been encapsulated into an isolated class (remember the sacred OOP principle that says “Encapsulate the concept that varies"?). Okay, now that you’re familiar with the inner workings of the above helper class, it’s time to start defining the validators. As they will share a lot of common functionality, they will be derived from a generic abstract parent. In the following segment I’m going to build this abstract validator class, so if you want to learn more details regarding this process, click on the link below and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|