Page 1 of 1

Where to check query string values?

Posted: Fri Jan 21, 2011 3:38 am
by social_experiment
In a recent project i thought about this issue, where to test the query string value? In this example the value retrieved from the query string looks like this

page.php?id=5

Code: Select all

if (checkValidId($_GET['id']) == 1) {
 // ----
 if (isset POSTbtn) {
  // ----
  modifyInformation()
 }
 else {
  // ----
  displayForm()
 }
}
else {
 // ----
 echo 'Invalid id';
}
The value of $_GET['id'] is tested before it is passed to the modifyInformation() function. If it is valid, the script continues processing. If 0 is returned, an error message is echoed to indicate that the value is not correct.

My question: Where is the best place to test for validity of a value (or values) retrieved from the query string? Obviously before the value is used to manipulate the database but do you create something like my example or do you do the checking in modifyInformation() or elsewhere?

Re: Where to check query string values?

Posted: Fri Jan 21, 2011 12:45 pm
by John Cartwright
My models will usually be able to validate themselves. I.e.,

Code: Select all

$user = new User();
$user->firstname = 'John';
$user->lastname = 'Cartwright';
$user->email = 'bademailformat.com';

if ($user->save()) {
   //success
} else {
   $errors = $user->getValidationErrors();
}
This is a good way to keep your business logic out of your controllers.

Re: Where to check query string values?

Posted: Sat Jan 22, 2011 12:51 am
by social_experiment
Yeah that looks much cleaner (and efficient), a question on the example you made, do you validate in save() method?

Re: Where to check query string values?

Posted: Sat Jan 22, 2011 11:24 am
by John Cartwright
social_experiment wrote:Yeah that looks much cleaner (and efficient), a question on the example you made, do you validate in save() method?
It is completely up to you how to implement it, but you generally want to have some schema of the data your expecting. Here is a very simplified version of what I generally do

Code: Select all

class User
{
   public function save() 
   {
      if ($this->validates()) {
         //save 
         return true;
      }
      return false;  
   }

   public function validate() 
   {
      $validator = new Validator();
      $validator->addRule('username', new Validator_Rule_NotEmpty());
      $validator->addRule('email', new Validator_Rule_Email());

      if (!$valid = $validator->isValid($this->_data)) {
         $this->_setValidationMessages($validator->getErrors());
      }
      
      return $valid;
   }
}