Does the I / O filter code go into the controller or domain model?

I have been using php for some time, but new to OO php. As an exercise for myself, I create a small MVC structure.

I understand that there is probably no final answer for this, but I wonder: where does the input filter / validation code belong?

Should it be part of the controller where the request is analyzed?

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

Any advice would be highly appreciated.

+4
source share
2 answers

Controllers usually process request data (GET / POST) and detect invalid forms, CSRF, missing fields, etc., for which the model should not bother. This is the most likely place where you write the bulk of your filter code; validation should only take place until the check for early failure has been verified (for example, do not send an email address to the model if it is not a valid email address).

Your domain’s objects can also provide validation checks (even filtering), which will reduce the responsibility of the dispatcher, but in most cases it’s easier for me personally to work with the model based on the contract (the model assumes that you pass legitimate values) because it’s easier to directly translate validation issues into certain form fields.

The model itself can also perform validation, although it differs from the above input filtering (and checking the type of content); for example, it can check if an email exists in the database, and not check its valid email address.

+1
source

The controller is not responsible for validation in any way, form or form. The controller is part of the presentation layer, which is responsible for interacting with the user. Do not ask about it.

Validation is mainly for objects where most of the domain’s business logic ends at the model level. Some verification is what might be called "data integrity checks" (for example, making sure the username is unique). These restrictions are performed by the database structure (for example, with a UNIQUE in this example or NOT NULL in some others). When you save a domain object using a data mapper (or some other storage template), it can raise some exceptions . These exceptions can also be used to set the error state for a specific domain object.

If you have a form, it will be bound to one or more domain objects that are validated when the form is submitted. Then, the current view requests information from the model level and, if an error condition has been established, displays appropriate warnings.

+4
source

All Articles