greenLizard
greenLizard

Reputation: 2346

Where to validate data Controller or Model in CodeIgniter

I know that the CI way of doing this is to validate against the rules in the controller, but I think this is not the ultimate approach. What would you recommend me to do follow the CI way or validate incoming data in the Model, so my model will always be protecting itself against bad data. My understanding of MVC is that controller don't have to keep any program logic, all the logic is implemented in the model. I will appreciate if you can explain in detail why both approaches are good and not and which one is recommended ?

Cheers

Upvotes: 2

Views: 1678

Answers (1)

Francis Avila
Francis Avila

Reputation: 31651

There is no silver bullet.

Validation in the model protects you against programatic sources of invalidation. However, users do not get direct access to your models but only through controllers and ultimately through forms. Most of the time you need additional validation which is specific to a certain form or a certain controller and which is inappropriate in a model.

This argues for a layer of validation outside the model. Ideally you can create a separate validation object (maybe tied to a specific form) which is used by the controller. Occasionally you may need additional validation in the controller itself.

Validation is not binary. There are many layers of validation and different types of validation necessary in different contexts. You may need validation in both the model and the controller.

Upvotes: 8

Related Questions