i am starting to put validation/sanitization in my codeigniter models, and before diving in too deep I am looking for some suggestions on best practices. the form validation
library for controllers is great, but obviously i don't want to rely on the controllers to send me good data.
currently I return bool values, TRUE (or data) on success, FALSE on failure, which makes it really hard to pass error messages back to the caller. I would like to get away from the FALSE on failure.
while definitely not an expert, i have started reading quite a bit on Exceptions and have come across them quite a bit with external libraries, and they seem like a good candidate for this. my question is, is this appropriate use of exceptions? are model errors exceptional errors?
a possible example:
<?php
class person_model extends CI_Model{
public function getPersonById($personId){
//check for int
if(!is_int($personId) OR $personId < 0){
throw new Exception('Invalid person ID');
}
//setup query
$this->db->select('*')
->where('personId', $personId);
//run query
$result = $this->db->get('person');
//failed to get
if(!$result){
throw new Exception('DB query failed');
//should i also return false?
return FALSE;
}
//got info
else{
return $result;
}
}
}
?>
thanks for the help!
EDIT:
I have to say I am quite surprised by the responses suggesting that data validation should only be done in the controller. Models are the last barrier to your data storage. The model is the data and the rules applying to that data, your application logic. Data validation seems like application logic to me. Also you may have many controllers accessing the same model method. Do you want to rely on both controllers implementing the same validation? That seems silly to me.
Also, not all data is coming from user input, some of it could be hardcoded into the script by your programmer writing the controller. What if they pass a string when your model is expecting an integer? Or pass an incorrectly formatted date? shouldn't the model say something about that.
I'm open to a discussion, but I feel data validation DEFINITELY belongs in the model. (in addition to the controller, and even the view (html5/javascript for convenience))