HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Basic PHP MVC setup for form submissions

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
mvcphpsetupforformsubmissionsbasic

Problem

I'd like your thoughts on this basic implementation of MVC. The view outputs a form, and when the page is loaded, the controller checks for a form submission and then updates the model accordingly. Finally, the view outputs the form again, grabbing the new values from the model.

One problem with this is that if the user refreshes the page, a submission will still happen because the $_POST['submitted'] flag is still sent. Ideally, I'd like to avoid this - is there a suggestion for using AJAX to make this work?

```
date = $date;
}

public function update_amount($amount) {
$this->amount = $amount;
}
}

class EntryController {
private $model;

public function __construct(EntryModel $model) {
$this->model = $model;
}

public function get_submission() {
if (!isset($_POST['submitted']))
return;

foreach ($_POST as $g => $k)
{
if ($g == 'form_date')
$this->model->update_date($k);
elseif ($g == 'form_amount')
$this->model->update_amount($k);
}

echo ("Sucessful submission");
}

}

class EntryView {
private $model;
private $controller;

public function __construct(EntryController $controller, EntryModel $model) {
$this->controller = $controller;
$this->model = $model;
}

public function output() {
$form_output =
'
Date: model->date . '">
Amount: model->amount . '">


';

return $form_output;
}
}

$model = new EntryModel();
$controller = new EntryController($model);
$view = new EntryView($controller, $model);

$controller->get_subm

Solution

Templates

Your HTML code should be separated out into a template file. You should do your best to avoid mixing HTML into your PHP, as your HTML will inevitably grow, and your PHP will get messier as a result.

Post/Get/Redirect

The pattern you are looking for is Post/Get/Redirect. You should always follow this pattern. When a user submits a form using POST, you should process the form, and then if it was successful, redirect them back to some page (possibly the form page again) with an added URL parameter.

E.g. http://example.com/contact-us?submitted=true

Then in your form code, you can check if the URL parameter is present, and show a success message.

Context

StackExchange Code Review Q#31538, answer score: 7

Revisions (0)

No revisions yet.