I am wondering about HTML form processing in MVC. I use Kohana at the moment, but the question is generic in nature. So I want to gather opionions and recommendations about two approaches :
-
Keeping procesing in action, that displays the form:
class Controler_Sample { public function action_one { $view = View::factory('form'); if($_POST) { $model = new Model_SomeModel; //validate try($model->values($_POST)->save(); { //on success go to action with success logic using post redirect get pattern $this->request->redirect('Sample/sucess') } catch(Exception $e) { //on fail attach error message to form view $view->set('errors',$e->errors); } } echo $view; } } -
Keeping form processing in other action, than this one displaying it
class Controler_Sample { public function action_one { //display form, with errors if there are anny passed in GET echo View::factory('form') set->('errors',$this->request->get('errors',FALSE); } public function action_two { if($_POST) { $model = new Model_SomeModel; //validate try($model->values($_POST)->save(); { //on success go to action two using post redirect get pattern $this->request->redirect('Sample/success') } catch(Exception $e) { //on fail create new hmvc call to action_one with errors in GET //im don't remember the syntax, let's assume it's here ok :D } } } } -
Other architecture that you preffer?
I see that the first approach is faster to type and process, but the second is more reusable – the action_two, that processes the form could be called from forms or ajax in other places in APP.
What do you think ?
I say the second approach is better.
It adheres to the single responsibility principle, and is you say yourself, it’s easier to reuse the code.