David Lidstone wrote:
Hi All
I seem to be writing a lot of this:
//======== SCRIPT =========
$var = $_POST['var'];
// validate $var
$foo = new foo;
$foo->setBar($var);
//======== CLASS ==========
class foo {
public function setBar($var) {
// validate $var
}
}
As you can see, the "issue" is that I am validating the input in my
script, and then again in my class... surely unwanted duplication!?
Obviously (I think!), I need to be validating at the level of my class,
so does anyone have a pattern / strategy to help ease the pain... a way
of using the validation in the class to validate the script and return
meaningful errors to the user?? Throwing errors and forcing the script
to catch them perhaps?
I have tried a few validation classes etc and they have not really
addressed this issue. Perhaps I should just live with it and get on with
it! :)
Many thanks for your help, David
Well, you could try looking at using exceptions:
//==== CLASS ====
class foo
{
public function setBar($var)
{
if ( var_is_NOT_a_valid_value_for_bar )
{
throw new Exception('Invalid value for bar in class foo');
}
}
}
// ===== Script =====
$var = $_POST['var'];
$foo = new foo();
try
{
$foo->setBar($var);
}
catch (Exception $e)
{
echo 'An error occurred: ',$e->getMessage(),"\n";
}
Take a look at http://www.php.net/manual/en/language.exceptions.php
--
Peter Ford phone: 01580 893333
Developer fax: 01580 893399
Justcroft International Ltd., Staplehurst, Kent
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php