For my very first post on this site, I’d like to introduce “The Command Structure.”

This is a pretty simple idea.  Anywhere your code has to do something or trigger something else to happen, there’s an explicitly stated “command” that is passed.  With that command, it’s easy to search or hop to certain parts of code to find what is going on.  It also separates code into nice easy-to-read and easy-to-understand segments.

Most of my programming examples will be in PHP.  It’s a popular, open source language, and it’s fast and stable.  Are other languages faster?  Probably.  Are other languages as widely used?  Sure.  PHP is mature, widely used, and easy to work with, therefore I love it.

Let’s say you have a simple PHP page that asks users to submit a form and you’re going to store the resulting data in a database.  Here’s how the command structure would work with that page:

<?php

include 'header.inc.php';
$command = $_REQUEST['command'];

if($command=='') {
	?>
		// display page, with form here
		<form action="<?=$_SERVER['PHP_SELF']?>" method='post'>
		<input type='hidden' name='command' value='save'>
		<input type='text' name='my_text_input_field'>
		<input type='submit' value='Save'>
		</form>
	<?
}

if($command=='save') {
	$query = "INSERT INTO ... SET `fieldname`='".mysql_real_escape_string($_REQUEST['my_text_input_field'])."'";
	mysql_query($query);
	header("Location: ".$_SERVER['PHP_SELF']."?command=thank");
	exit;
}

if($command=='thank') {
	echo "Thank you for adding data to our database";
}

include 'footer.inc.php';

?>

So this is obviously a rough example, but it’s easy to see how on one page you can handle multiple operations, and it’s easy to see what is going to happen when, where, and how. And for those of you keeping track at home, you’re probably shouting, “Hey, that’s not even MVC code!” And you’re right, technically it isn’t. There’s no model at all, and the controller and view are in the same file. That’s OK for now, I’m just illustrating a basic programming point before moving on to more advanced topics.

In the future I’ll be covering how to handle object creation, writing to databases, user input requirements, and more.

March 27th, 2013

Posted In: Basics

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: