As I said in previous segment, the final touch that I plan to give to the sample form helper class defined before is to provide it with the ability to retrieve and delete the array of errors that might have been stored during the entire validation process. These tasks will be performed by two brand new methods called “getErrors()” and “clear(),” and their respective definitions have been included in the following code fragment: (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(); } } Mission accomplished. Now, the form helper class includes the convenient methods mentioned before, along with one more called “getErrorString().” As its name suggests, this method can be used for fetching all the stored errors in the form of a string. With the form helper already set, the next step required to implement the Strategy pattern is to define the different validation classes that will be injected into the helper via its “addValidator()” method. The first of these classes will be discussed in the upcoming part of the series; it will be responsible for validating integers, or expressed in more technical terms, will implement an integer validation strategy. Final thoughts That’s all for now. In this first part of the series, I provided you with a quick introduction to validating incoming data via the Strategy design pattern. Since my goal here is to develop a modular application that permits you to check input data using different strategies represented by multiple validator objects, in the following article I’m going to start creating the originating classes of those objects, which will come in handy for validating typical data types, including integers and float numbers, email addresses and URLs as well. Now that you know the topics that will be covered in the next tutorial, you don’t have any excuses to miss it!
blog comments powered by Disqus |
|
|
|
|
|
|
|