Posted by on in iDevelop, PHP | 0 comments

When I was first started playing around with NodeJS few months back, I came across Mongoose, a really neat ODM for MongoDB. You just needed to define the schema for each entity and pass it to that model and Mongoose would validate all data against that schema. That concept kinda intrigued me, as you wouldn’t need to create your own validation for the data.

For a couple of months now, I’ve been playing around with Laravel and it has an excellent ORM called Eloquent. Now as far as creating a model goes, it is simple, easy to use. But no validation against a schema or set of rules. So far I’ve been using a Validation service that I’d create & its sub-classes (one for each model with model specific rules). But I’ve been thinking why not do this inside the model itself?

So the base model would be something like (not exact code):

php
/app/models/BaseModel.php

  1. class BaseModel extends Eloquent {
  2.     protected $_rules = array(
  3.         'create' => array(),
  4.         'update' => array(),
  5.     );
  6.  
  7.     protected $_custom_errors = array();
  8.  
  9.     protected function _validate( $data, $rules ) {
  10.         $validation = Validator::make( $data, $rules, $this->_custom_errors );
  11.  
  12.         if ( $validation->fails() ) {
  13.             //data validation failed, throw an exception
  14.             //ValidationException is a custom exception which
  15.             //can accept MessageBag instance as first argument
  16.             throw new ValidationException( $validation->messages() );
  17.         }
  18.  
  19.         //all good & hunky dory
  20.         return true;
  21.     }
  22.  
  23.     public function create( array $attributes ) {
  24.         try {
  25.             $this->_validate( $attributes, $this->_rules['create'] );
  26.         } catch ( ValidationException $e ) {
  27.             //we would want to catch it in controller
  28.             //its of no use here, so lets re-throw
  29.             //the exception
  30.             throw $e;
  31.         }
  32.  
  33.         //all good
  34.         return parent::create( $attributes );
  35.     }
  36. }

and then each model can extend this BaseModel and define their individual rules for data validation:

php
/app/models/User.php

  1. class User extends BaseModel {
  2.     protected $_rules = array(
  3.         'create' => array(
  4.             'username' => array(
  5.                 'required', 'unique', 'min:8', 'max:20',
  6.             ),
  7.             'password' => array(
  8.                 'required', 'min:8', 'confirmed',
  9.             ),
  10.             'password_confirmation' => array(
  11.                 'required', 'min:8',
  12.             ),
  13.         ),
  14.         'update' => array(
  15.             'password' => array(
  16.                 'min:8', 'confirmed',
  17.             ),
  18.             'password_confirmation' => array(
  19.                 'min:8',
  20.             ),
  21.         ),
  22.     );
  23. }

and that would be it. Now if a new user is to be created then all that will need to be done is:

php
…trollers/UsersController.php

  1. class UsersController extends BaseController {
  2.     public function create() {
  3.         try {
  4.             User::create( Input:all() );
  5.         } catch ( ValidationException $e ) {
  6.             //Ooo, exception caught
  7.             //do something about it
  8.             return Redirect::back()
  9.                     ->withInput( Input:except( 'password', 'password_confirmation' ) )
  10.                     ->withErrors( $e->get_errors() );
  11.         }
  12.  
  13.         //all good, user created
  14.         return Redirect::back()
  15.                 ->with( 'message', 'Registration Successful' );
  16.     }
  17. }

This would be a good way of doing things. A couple of days back I came across 2 packages – Ardent & Magniloquent. Both of these are layers that sit on top of Eloquent do the same thing (Magniloquent was inspired by Ardent but is a bit more super-charged), they make models super-charged ie., you define validation rules in your models and they take care of validation before data is saved. The code would be streamlined just like I’ve shown above.

But is this the right way to do things? A model’s role is to act as a bridge between app and data source, to make data available. Data validation is not its job. What happens to Single Responsibility?

There seem to be more than one school of thoughts on this one, some advocate this approach while some don’t. I guess in the end it comes down to personal preference and which school of thought you subscribe to.