开发者

MVC [Zend Framework]: where to apply filtering and validation

I've got (I hop开发者_运维百科e) a very simple question for experts at MVC structure:

where to apply input filtering and validation? Controller or model?

I've read a lot of tutorials and manuals on filtering user input, but haven't noticed a lot of discussion where it should be applied. When using forms, it's simple, actually almost everything is done for you by Zend_Form via Zend_Filter and Zend_Validate.

But when I have to filter single value from user input and pass it to the model, what is the best practice, to do cleaning before passing it to the model, or in the model itself?

Lets assume I am creating a model, that other people will use too, and it is doing some important work on filesystem. Am I 100% sure other people will properly prepare parameters before passing it to the model? I am not, so the best would be cleaning parameters in the model itself.

But that's just my thoughts, and as I said before, I'd like to hear yours, right from the masters of the profession ;)

Nice day.


IMHO it depends on whether you know in advance the kind of validation you will have to do.

If it's something that could be expressed as a regex, leave it in the controller, otherwise I think the model should be its place.

Examples.

You have to validate an email address: controller, so the model can be passed some sanitized input and just take care of the actual processing.

You have to check whether a path in the filesystem exists: the controller will take care of seeing if it's a well-constructed path; the model will check if it actually exists in the filesystem in question.

You have to check whether an user-provided string $x can produce an hash $y you stored somewhere: model.


I would say in the controller. My understanding is that models should be constructed under the assumption that they are being given valid data to work with (but with sensible precautions in place in case they're not, such as using prepared statements for database access), and leaving the actual validation of data to an outside agent, in this case the controller.


Typically you do it in the controller. Model should be dealing with legit, usable data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜