Separate input from processing

Tags
Summary

Put input and validation in one program. Put processing code in another. Use the session to send data from one to the other.

Situation

You have an add/edit form for a business entity in a page, along with its validation logic. The program is getting complex. Adding DB save code would make it even messier.

Action

You add/edit form will have code that runs when all the validation checks have passed. You want to save the data to a DB. Rather than doing it on that page, put the data into the session, and jump to a separate processing page.

  • session_start();
  • ...
  • // Is everything OK?
  • if ($errorMessage == '') {
  •     // Yes.
  •     // Save the data.
  •     // Put it into session variables.
  •     $_SESSION['goat_id'] = $goatId;
  •     $_SESSION['goat_name'] = $goatName;
  •     $_SESSION['goat_gender'] = $goatGender;
  •     $_SESSION['goat_fave_comedian'] = $goatFaveComedianId;
  •     $_SESSION['goat_comments'] = $goatComments;
  •     $_SESSION['goat_clubs'] = $goatClubMemberships;
  •     // Off to processing.
  •     header('Location: goat-save.php');
  •     exit();
  • }

In goat-save.php:

  • session_start();
  • require_once 'library/useful-functions.php';
  • // Grab data to save.
  • $goatId = $_SESSION['goat_id'];
  • $goatName = $_SESSION['goat_name'];
  • $goatGender = $_SESSION['goat_gender'];
  • $goatFaveComedianId = $_SESSION['goat_fave_comedian'];
  • $goatComments = $_SESSION['goat_comments'];
  • $goatClubMemberships = $_SESSION['goat_clubs'];
Explanation

Splitting the code has several advantages:

  • It makes the add/edit page simpler, and easier to think about.
  • The save page is reusable. The data can come from a form, from another system... as long as the data gets into the session, the save page doesn't care where it comes from.
  • Different people can write each page. They can work at the same time, reducing overall project completion time.
Where referenced