phpmodel-view-controllervalidationinput-filtering

Does input filter / validation code belong in the controller or the domain model?


I have been using php for awhile but am new to OO php. As an exercise for myself I am building a small MVC framework.

I realize there is probably not a definitive answer for this, but I am wondering: Where does the input filter / validation code belong?

Should it be a part of the controller, where the request is parsed?

Or is it more appropriate to have filter / validation code in the domain model, so that each domain object is responsible for validating its own info.

Any advice would be much appreciated.


Solution

  • Controllers would typically handle request data (GET / POST) and detect invalid form submissions, CSRF, missing fields, etc. for which the model should not be concerned about. This is the most likely place where you would write the bulk of mostly your filtering code; validation should only go as far as sanity checks for early failure (e.g. don't bother to send an email address to the model if it's not a valid email address).

    Your domain objects may also provide validation hooks (even filtering), which would reduce the controller's responsibility, but in most cases I personally find it easier to work with a contract based model (the model assumes you're passing legit values) because it's easier to directly translate validation issues to specific form fields.

    The model itself may do validation as well, albeit different from aforementioned input filtering (and content type validation); for instance, it might check whether an email exists in the database rather than making sure it's a valid email address.