Lets start out and assume you have something like this at the top of your page:
$action = $_GET['action'];
Now we have $action equal to the action you wish to perform.
You could use a collection of if statements to test $action and then do something. Disadvantage: pain in the butt to read and update if you have a lot of these. For like 1 test, it works great. For 3 or more, I'd use one of the other methods.
Use switch. I had been using this for a year and it worked. But if you have a lot of tests to perform, the switch code gets ugly pretty fast (not as fast as the #1 approach, but almost as bad). The cool part about switch is you can use the default statement. Kinda like this:
switch($action)
{
case 'read':
doread();
break;
default:
dodefault();
break;
} // end switch($action)
So the switch provides a hint of security if someone starts messing with your action variable. But as you see, for 1 test and a default, we're up to 9 lines of code and its only going to get worse.
I also ran into an article about how you should avoid using if and switch statements for a purpose similar to this. The idea was it gets messy and difficult to support.
- Using function calls and function_exists(). I stumbled upon this idea and didn't think it would work out well and gave it a whirl anyways. It has worked out really really well (for me at least). The idea is for each action, you call a function. But using variable function names, you can use $action to help define what function you are actually going to call (probably doesn't make much sense so I'll show some code):
$action = $_GET['action'];
$function = 'action_' . $action; // creates a string: action_ and then your action data
// check if this function exists:
if(function_exists($function))
$function($_GET, $_POST); // I like to pass along get and post for form handling
else
action_Default($_GET, $_POST); // function doesn't exist so call the default (similar to the switch default as seen above)
// functions:
function action_Default($get, $post)
{
// show your default page/form
} // end
function action_doread($get, $post)
{
// another function that does something
} // end
The cool part about this approach is if you need to add functionality, you just add another function. You don't have to fiddle with if statements or case statements. Plus, if you need to troubleshoot, you just need to know the name of $action and then look up its function.
I put "action" before the actual $action variable because I want to make sure the user can not tweak the $action variable to point to PHP's collection of functions. You can use whatever you like instead of "action" (I normally use "Do_" which works well for me).
Then its just a matter of plugging in the code you want that function to do.