April 5, 2007

Validating a model using Zend_Validate_Interface

Filed under: PHP — Marcus @ 10:23 am

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;

Code (php)
  1.  
  2. class SampleModel{
  3.   public $variable;
  4.   public $othervariable;
  5.   public $integer;
  6.   public $constraints = array(
  7.     ‘variable’ => ‘Zend_Validate_Alnum’,
  8.     ‘othervariable’ => ‘Zend_Validate_EmailAddress’,
  9.   );
  10.  
  11.   public function __construct()
  12.   {
  13.     $this->constraints[‘integer’] = new Zend_Validate_Between(4, 8);
  14.   }
  15. }

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;

Code (php)
  1.  
  2. class ModelValidator implements Zend_Validate_Interface
  3. {
  4.   /**
  5.    * Array of validation failure messages
  6.    *
  7.    * @var array
  8.    */
  9.   private $messages = array();
  10.   /**
  11.    * Is the model valid?
  12.    * @return boolean
  13.    */
  14.   public function isValid($model)
  15.   {
  16.     // see if the user has defined any constraints at all
  17.     if (!isset($model->constraints)) {
  18.       return true;
  19.     }
  20.     $isValid = true;
  21.     $this->messages = array();
  22.     // Process the constraints otherwise
  23.     foreach ($model->constraints as $property => $constraint) {
  24.       // If the constraint is a string, we create an instance
  25.       // of the class it describes. If it’s an object, we
  26.       // use that instead
  27.       if (is_string($constraint)) {
  28.         $constraint = new $constraint;
  29.       }
  30.     if (!$constraint->isValid($model->$property)) {
  31.         $this->messages[$property] = $constraint->getMessages();
  32.         $isValid = false;
  33.       }
  34.     }
  35.     return $isValid;
  36.   }
  37.  
  38.  /**
  39.   * Get validation erro messages
  40.   *
  41.   * @return array
  42.   */
  43.   public function getMessages()
  44.   {
  45.     return $this->messages;
  46.   }
  47. }

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.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

You must be logged in to post a comment.

.

Powered by WordPress