I’ve searched around but there doesn’t seem to be a clear consensus on which one is better. Currently, all the HTML forms on the site point to a single PHP file. Each form has a hidden input specifying the action (e.g. ‘user-login’, ‘user-logout’), and the PHP file calls methods from that.
So my question is: Should I point each form back to itself, related forms to a single file or all forms to a single file? And in terms of MVC, should processing take place in the controller or form?
You should point everything to
index.php, which then delegates other components (controllers in MVC terms) to take care of the processing. The controller will then decide which view it wants to render.index.phpwould be in this case something we call the front controller. (note: below I am recommending ZF1 as a learning platform. ZF1 has a “front controller” class. Some people may argue that THAT one is the front controller andindex.phpis what they call the entry script. In my opinion, that is only the second “front” controller. Nevertheless, both opinions are controversed, so make your own opinion).In terms of OOP first and foremost: the object is the only one who knows how to validate its own data (the principle of self-containment), so the form should validate itself. If it’s about a model, the model should be called by either the controller, or the form – it’s a matter of taste. No matter which way, the same principle applies: you feed the Model with data and call its validation method.
As you may have noticed, the
Formclass is aModel.Don’t let yourself fooled by the hype called MVC. Respect the OOP principles above all.
Regarding MVC: the MVC pattern says: the controller only coordonates the other components, for instance it takes the input, creates a Form instance, and calls the Form’s validation method.
I advise you to use a framework to better see how all these pieces work together. The best would be zend framework 1, which has little to do with real life requirements, BUT which is a masterpiece in terms of patterns and practices.
Maybe ZF2 will change that mistake with the extra front controller.
Looking at the other answers, I feel the need to clarify some terminology used in my answer:
Modelis a model. There’s plenty of documentation about MVCFormis a subclass ofModel. It takes care of the validation. It may also have a methodForm::__toString()which renders the HTML form in the view (the V in MVC)To recap, the overall execution flow would look like this:
<form action ...Controllercoordinates all the actions, calling theModel::validate()of one or many models (includingForm, which is also aModel)Controllerchoses torender()a view (a html file), which could contain a call toForm::__toString(), in which case theFormis a hybrid ofModeland “renderer”.That’s it, basically. Different frameworks have different data/execution flow. ZF1’s looks like this for instance: http://www.slideshare.net/polleywong/zend-framework-dispatch-workflow