views:

156

answers:

3

I'm using a PHP MVC Framework, and I've been just lumping all my validation functions in a helper class which get called when I need them.

However, isn't the Model for logic about working with data, not exclusively databases? Would it make more sense to put the validation functions in one of my models?

Thanks

A: 

Yes, I would put validation in the models. However, you didn't mention which MVC framework you're using. If you're using CodeIgniter and its built in validation, it kind of forces you to validate in the controller.

jimyi
+3  A: 

The Model layer is for modelling how your application would work in the real world, so it's not just necessarily for dealing with data.

A common approach to validation functions is to create a Validator class for each type of validation you wish to perform. The Validators should implement an interface, so that any code utilizing a Validator object can be assured that they all work the same.

Something like this:

interface iValidator
{
    public function validate($mixed);
    public function getMessage();
}

class Validator_Email implements iValidator
{
    public function validate($data)
    {
         //validate an email address
    }

    public function getMessage()
    {
     return 'invalid email address.';
    }
}

class Validator_PositiveInteger implements iValidator
{
    public function validate($data)
    {
     return ctype_digit((string) $data) && $data != 0; 
    }

    public function getMessage()
    {
     return 'must be a positive integer';
    }
}

If you're using a framework, it may already have validation classes that you can utilize or extend in a similar manner.

zombat
A: 

Validation in this case is coming from a user input - you're going to want to validate the same input 'type' for many models, potentially. I'd go with a set of Validation classes (see Zend_Validate) and use them as input filters/validators in your Controller.

Since its In/Out manipulation, I see Controller as the place for that. Model should be more concerned about making sure your data is stored and retrieved.

Justin