Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP and Codeigniter - How do you check if a model exists and/or not throw an error?

Example #1

bschaeffer'sanswer to this question - in his last example:

$this->load->model('table');
$data = $this->table->some_func();
$this->load->view('view', $data);

How do you handle this when 'table' doesn't exist?


Example #2

    try {
        $this->load->model('serve_' . $model_name, 'my_model');
        $this->my_model->my_fcn($prams);

        // Model Exists

    } catch (Exception $e) {
        // Model does NOT Exist
    }

But still after running this (obvously the model doesn't exist - but sometimes will) it fails with the following error:

An Error Was Encountered

Unable to locate the model you have specified: serve_forms


I am getting this function call by:

1) Getting some JSON:

"model_1:{"function_name:{"pram_1":"1", "pram_2":"1"}}

2) And turning it into the function call:

$this->load->model('serve_' . "model_1", 'my_model');

3) Where I call:

$this->my_model->function_name(pram_1=1, pram_2=1);

SOLUTION

The problem lies in the fact that CodeIgniter's show_error(...) function displays the error then exit; ... Not cool ... So I overrode: model(...) -> my_model(..) (you'll get errors if you just override it) and removed the show_error(...) because for some reason you can't override it - weird for Codeigniter). Then in my_model(...) made it throw an Exception

My personal opinion: the calling function should return show_error("message"); where show_error returns FALSE --- that or you could take out the exit; - and make show_error(...) overridable

like image 204
Wallter Avatar asked Aug 10 '11 21:08

Wallter


People also ask

How check model loaded or not in CodeIgniter?

You can use the log_message() function.

What is error handler in CodeIgniter?

CodeIgniter lets you build error reporting into your applications using the functions described below. In addition, it has an error logging class that permits error and debugging messages to be saved as text files. Note. By default, CodeIgniter displays all PHP errors.

How can I get database error in CodeIgniter 3?

$query = "some buggy sql statement"; $this->db->db_debug = false; if(!@ $this->db->query($query)) { $error = $this->db->error(); // do something in error case }else{ // do something in success case } ... Save this answer.

Can we call model from view in CodeIgniter?

You can use it inside loop.


1 Answers

You can see if the file exists in the models folder.

$model = 'my_model';
if(file_exists(APPPATH."models/$model.php")){
   $this->load->model($model);
   $this->my_model->my_fcn($prams);
}
else{
  // model doesn't exist
}
like image 85
Rocket Hazmat Avatar answered Sep 23 '22 15:09

Rocket Hazmat