I was wondering if someone can show me a good way to handle errors in my PHP app, that i am also easily able to reuse in my codes.
So far i have been using the following functions:
Inline Errors
function display_errors_for($fieldname) {
global $errors;
if (isset($errors[$fieldname]))
{
return '<label for="' .$fieldname. '" class="error">' . ucfirst($errors[$fieldname]). '</label>';
} else {
return false;
}
}
All Errrors
function display_all_errors($showCounter = true) {
global $errors;
$counter = 0;
foreach ($errors as $errorFieldName => $errorText)
{
if ($showCounter == true)
{
$counter++;
echo '<li>' . $counter . ' - <label for="' .$errorFieldName. '">' .$errorText. '</label></li>';
} else {
echo '<li><label for="' .$errorFieldName. '">' .$errorText. '</label></li>';
}
}
}
I have a $errors = array(); defined on the top of my global file, so it is appended to all files.
The way i use it is that if i encounter an error, i push a new error key/value to the $errors array holder, something like the following:
if (strlen($username) < 3) {
$errors['username'] = "usernames cannot be less then 3 characters.";
}
This all works great and all, But i wondering if some one has a better approach for this? with classes? i don't think i want to use Exceptions with try/catch seems like an overkill to me.
I'm planning to make a new app, and i'll be getting my hands wet with OOP alot, though i have already made apps using OOP but this time i'm planning to go even deeper and use OOP approach more extensively.
What i have in mind is something like this, though its just a basic class i will add further detail to it as i go deeper and deeper in my app to see what it needs.
class Errors
{
public $errors = array();
public function __construct()
{
// Initialize Default Values
// Initialize Methods
}
public function __destruct()
{
//nothing here too...
}
public function add($errorField, $errorDesc)
{
if (!is_string($errorField)) return false;
if (!is_string($errorDesc)) return false;
$this->errors[$errorField] = $errorDesc;
}
public function display($errorsArray)
{
// code to iterate through the array and display all errors.
}
}
Please share your thoughts, if this is a good way to make a reusable class to store and display errors for an entire app, or is getting more familiar with exceptions and try/catch my only choice?