I am wondering about HTML form processing in MVC. I use Kohana at the moment, but the question is generic type. So i wanna 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
}
}
}
}Other architecture that you preffer?
I see that the first approach is faster to type and process, but second 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.
…………………………………….
Use the second approach. Most webpages implement the Redirect-After-Post methodology to omit double submission problems and to fix refresh. Therefore the post processing would redirect anyways to a result set. As Ikke said the single responsobility principle is also a good way to design methods because it is better to understand methods like process_post and show_form than a weird mix of if else trees which evolve subsequently to a wood of if else statements.
…………………………………….
To further, If you wish to use the same logic in two different controllers then you can use Command Pattern. Simple create a command and use it at two different places.