Passing forms vs raw input to service layer
Asked Answered
E

1

0

Is it better to validate a form and pass its filtered input to the service layer, or to pass the raw input to the service layer, and have the service validate the input (with or without a form instance)?

Obviously, if it's the latter, the controller still needs access to the form so that it can be sent to the view for rendering. If so, would you just access the form via the service ($service->getRegistrationForm())?

See also:

Emblematize answered 20/10, 2013 at 14:54 Comment(0)
P
0

The Form itself should handle the validation, ZF2 has methods on the Form class that enable this.

In an action on a controller that expects some kind of data from a form one of the first things I do is validate the form ($form->isValid()). If the form is not valid the controller will handle this immediately. Normally this involves jumping straight to returning the ViewModel with the form (which now contains data + validation results) so that the user can see any validation errors.

I don't see why'd you bother going any further without checking to see if you've got valid data or with data you know to be invalid. In fact the data might even be malicious (CSRF, which is handled by form validation).

Basically the issue of passing raw vs filtered input never really comes up.

Pretext answered 21/10, 2013 at 0:10 Comment(1)
That's the way I do it as well. A comment on GitHub just made me wonder if I was doing the right thing. I'm just thinking of situations where the services are used outside of the MVC context, for example in web services. In this case you would have to duplicate the filtering, validation, access control, etc. which is not ideal. Maybe I'm over-thinking things ... it happens all the time. :-)Emblematize

© 2022 - 2024 — McMap. All rights reserved.