On Thu, Mar 27, 2008 at 5:36 AM, David Lidstone <dnews@xxxxxxxxxxxx> 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 > > -- > PHP General Mailing List (http://www.php.net/) > To unsubscribe, visit: http://www.php.net/unsub.php > > I used to have this issue too. After years of coding and studying I've realized that the validation belongs where you get the user input. It doesn't belong in your class. Your class should just assume the parameters are exactly what you expect. Your burden is to always make sure that data is pristine before it gets injected. If you don't then you're going to end up with a mess. Your class will get bloated with unnecessary error handling code. Of course this isn't a 100% solution. Sometimes you do still need to check the parameters. So wherever you start using input data that is where you validate. That is where you handle errors if something is wrong such as re-displaying the form. Don't use the values inside your code if it is wrong. This way you can see it is very obvious what you're using and that it is clean and how you're dealing with it if it is wrong. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php