You could do it that way, but it could be improved. Having the actual capsule of validators, their own validation logic is good. Extending them from the base class is not. Let it implement an interface instead. Thus, any class can be a Validator.
interface IValidate { public function validate($value); }
Your validators will look like this:
class IsNumeric implements IValidate { public function validate($value) { return is_numeric($value); } }
and
class GreaterThan implements IValidate { protected $_value; public function __construct($value) { $this->_value = $value; } public function validate($value) { return $value > $this->_value; } }
You will still have the main Validator class. Unlike your example, the Validator below accepts several Validators, which allows you to create a filter chain.
class Validator implements IValidate { protected $_validators; public function addValidator(IValidate $validator) { $this->_validators[] = $validator; return $this; } public function validate($value) { foreach($this->_validators as $validator) { if ($validator->validate($value) === FALSE) { return FALSE; } } return TRUE; } }
And it can be used as:
$validator = new Validator; $validator->addValidator(new IsNumeric) ->addValidator(new GreaterThan(5)); var_dump( $validator->validate('ten') );
The above is mainly a Team Template . And due to the fact that Validator implements Ivalidate, it is also a Composite . You can take the Validator chain on top and put it in another Validator chain, for example
$numericGreaterThanFive = new Validator; $numericGreaterThanFive->addValidator(new IsNumeric) ->addValidator(new GreaterThan(5)); $otherValidator = new Validator; $otherValidator->addValidator(new Foo) ->addValidator(new Bar) ->addValidator($numericGreatherThanFive);
For convenience, you can add a static factory method to create validators with valid control command objects (as shown elsewhere).
On the side: Zend Framework already has a large number of validators that you can build on . Since ZF is a component library, you can use them without transferring the entire application to ZF.
Gordon
source share