Organized Form Handling
Posted: Thu May 31, 2007 8:07 pm
This is something that I've been trying for the life of me to make look pretty.
Classes look pretty.
Objects running functions look pretty.
Small echoes based on ternary operators here and there look pretty.
Includes and requires look pretty.
But long lists of nested ifs and elses checking for isset(), !empty(), and whether or not something was properly updated, then creating an error message for later display looks ugly.
Once, what I did was separate the form handling into the class that it affected. The class would have a function Update() which would take the $_POST array as a parameter, and return constants (or an array of constants) to give me the results.
Then, I'd sort through the results in the page through a switch statement (or foreach if it was an array), and output the appropriate error messages.
That is the neatest that I've ever made it and I liked being able to call a function return instead of nested ifs. However, it's definitely the less efficient of the two options. Also, I don't feel that it separates functionality from the form because the Update() function ends up being extremely application specific.
I was just curious to know how you guys are doing yours. I tried to get away from the method I just displayed, but I'm seriously considering going back to it.
Classes look pretty.
Objects running functions look pretty.
Small echoes based on ternary operators here and there look pretty.
Includes and requires look pretty.
But long lists of nested ifs and elses checking for isset(), !empty(), and whether or not something was properly updated, then creating an error message for later display looks ugly.
Once, what I did was separate the form handling into the class that it affected. The class would have a function Update() which would take the $_POST array as a parameter, and return constants (or an array of constants) to give me the results.
Code: Select all
function Update($post)
{
if(!isset($post['username']) || !isset($post['password']))
{
return ERROR_FILLED;
}
if(!$this->Valid($post['username'], $post['password']))
{
return ERROR_INVALIDUSER;
}
return SUCCESS;
}Code: Select all
// Attempt to update
if(!empty($_POST))
$result = $pUser->Update($_POST);
if($result == SUCCESS) header('Location: somewhere else');
...
switch($result)
{
case ERROR_FILLED: echo 'Fill it up, man.'; break;
case ERROR_INVALIDUSER: echo 'Who do you think you are? Scram.'; break;
case SUCCESS: /* If header redirect didn't work */ echo 'Go <a href="somewhere else">here</a>'; break;
}I was just curious to know how you guys are doing yours. I tried to get away from the method I just displayed, but I'm seriously considering going back to it.