[PHPwestoz] Hellooooo? (error handling)
Samuel Cochran
sj26 at sj26.com
Tue Jan 25 14:24:02 UTC 2005
Nicolas Connault wrote:
> Leon Brooks wrote:
>
>> On Tuesday 25 January 2005 10:40, Nicolas Connault wrote:
>>
>>> I need your opinion on the best:
>>> * Error Handling class
>>
>> echo '</table></table><h1>There has been an error!</h1></body></html>';
>> exit;
>>
>> Grins, ducks, runs.
>
> Hum . . . I need Object-Oriented programming, here . . . this is not
> helping!
Well, I don't know about OOP, but I generally use:
<?php
$errors = array();
if (error1($_POST['field']))
{
$errors['field'][] = "This is a horrible error";
}
if (error2($_POST['field']))
{
$errors['field'][] = "This is another horrible error";
}
else if (error3($_POST['field']))
{
$errors['field'][] = "This is yet another horrible error";
}
if (empty($errors['field']))
{
// handle data
}
// ...
?>
<form>
<?=(!empty($errors) ? '<p>There were errors. Please fix and try
again.</p>' : '')?>
Field: <input type="..." name="field" value="<?=$_POST['field']?>" /><br />
<?php if (!empty($errors['field'])) { ?>
<ul><li><?=implode('</li><li>', $errors['field'])?></li></ul>
<?php } ?>
<!-- ...and repeat -->
</form>
This allows for great flexibility in terms of error checking, and also
in presentation, as the error array is just a bunch of strings.
I also tend to use $errors[''] or $errors['.'] as a gobal errors field,
presented at the top of the form, or such.
This could be converted into an object-orientated solution, depending on
how you're handling your data inputs - for example, an OOP forms
implentation coule implement error members on all objects, and check for
the existence of errors when outputting the form. Errors could be added
to form objects, as well as input objects. validate() and handle() (or
equiv.) could add to these. The error member could either be a static
string array, or an array of Error objects, your choice.
There you go :P
-- Sam
More information about the PHPwestoz
mailing list