Note that there are some explanatory texts on larger screens.

plurals
  1. POHow should i handle errors in my Codeigniter Models?
    primarykey
    data
    text
    <p>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 <code>form validation</code> library for controllers is great, but obviously i don't want to rely on the controllers to send me good data.</p> <p>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.</p> <p>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?</p> <p>a possible example:</p> <pre><code>&lt;?php class person_model extends CI_Model{ public function getPersonById($personId){ //check for int if(!is_int($personId) OR $personId &lt; 0){ throw new Exception('Invalid person ID'); } //setup query $this-&gt;db-&gt;select('*') -&gt;where('personId', $personId); //run query $result = $this-&gt;db-&gt;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; } } } ?&gt; </code></pre> <p>thanks for the help!</p> <p>EDIT:</p> <p>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.</p> <p>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.</p> <p>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))</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload