Validating a model using Zend_Validate_Interface
One thing I like about Grails (being based on rails, I assume it stems from there…) is that it allows quite easy definition of constraints that the model classes should adhere to. Taking that idea, consider the following;
-
-
class SampleModel{
-
public $variable;
-
public $othervariable;
-
public $integer;
-
‘variable’ => ‘Zend_Validate_Alnum’,
-
‘othervariable’ => ‘Zend_Validate_EmailAddress’,
-
);
-
-
public function __construct()
-
{
-
$this->constraints[‘integer’] = new Zend_Validate_Between(4, 8);
-
}
-
}
The idea is that you can define simple validators by supplying the class name, or more complex validators by declaring them in the constructor. This allows for custom validator declarations, or chained validators using Zend_Validate.
The next part to this is actually doing something with the constraints, and here’s where mixins would be ultra handy. The current implementations of mixins don’t really float my boat, so instead I’ll use a separate validator;
-
-
class ModelValidator implements Zend_Validate_Interface
-
{
-
/**
-
* Array of validation failure messages
-
*
-
* @var array
-
*/
-
/**
-
* Is the model valid?
-
* @return boolean
-
*/
-
public function isValid($model)
-
{
-
// see if the user has defined any constraints at all
-
return true;
-
}
-
$isValid = true;
-
// Process the constraints otherwise
-
foreach ($model->constraints as $property => $constraint) {
-
// If the constraint is a string, we create an instance
-
// of the class it describes. If it’s an object, we
-
// use that instead
-
$constraint = new $constraint;
-
}
-
if (!$constraint->isValid($model->$property)) {
-
$this->messages[$property] = $constraint->getMessages();
-
$isValid = false;
-
}
-
}
-
return $isValid;
-
}
-
-
/**
-
* Get validation erro messages
-
*
-
* @return array
-
*/
-
public function getMessages()
-
{
-
return $this->messages;
-
}
-
}
So that will run through all the defined constraints and let us know if we’re valid or not. Also, being an implementor of Zend_Validator_Interface, it can be chained along with other validator calls. Useful… for me anyway.