PHP和Codeigniter - 如何检查模型是否存在和/或不会抛出错误? [英] PHP and Codeigniter - How do you check if a model exists and/or not throw an error?
问题描述
示例#1
bschaeffer的
回答这个问题 - 在他的最后一个例子中:
$这 - >负载>模型( '表');
$ data = $ this-> table-> some_func();
$ this-> load-> view('view',$ data);
当'table'
不存在?
示例#2
try {
$ / pre
$ this-> load-> model('serve_'。$ model_name,'my_model');
$ this-> my_model-> my_fcn($ prams);
//模型存在
} catch(异常$ e){
//模型不存在
}
但是,运行后仍然存在(但是有时候会出现这种模式),它会失败并出现以下错误:
发生错误
无法找到模型您已经指定:serve_forms
我正在通过以下方式获取此函数调用:
1)获取一些JSON:
model_1:{function_name:{pram_1:1,pram_2:1}}
2)并将其转换为函数调用:
$ this-> load->模型('serve_'。model_1,'my_model');
3)我在哪里打电话:
$ this-> my_model-> function_name( pram_1 = 1,pram_2 = 1);
解决方案
问题在于CodeIgniter的
show_error(...)
函数显示错误,然后exit;
...不好...所以我突破:model(...)
- >my_model(..)
(如果你只是重写它,你会收到错误),并删除了show_error(...)
,因为某些原因你不能覆盖它 - 对于Codeigniter很奇怪)。然后在my_model(...)
中使它抛出异常
我的个人意见:调用函数应该
return
其中show_error返回
show_error(message);FALSE
---或
您可以取出退出;
- 并使show_error(...)
可覆盖
解决方案存在于模型文件夹中。
$ model ='my_model';
if(file_exists(APPPATH。models / $ model.php)){
$ this-> load-> model($ model);
$ this-> my_model-> my_fcn($ prams);
}
else {
//模型不存在
}
Example #1
bschaeffer's
answer 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 thenexit;
... Not cool ... So I overrode:model(...)
->my_model(..)
(you'll get errors if you just override it) and removed theshow_error(...)
because for some reason you can't override it - weird for Codeigniter). Then inmy_model(...)
made it throw an ExceptionMy personal opinion: the calling function should
return show_error("message");
where show_error returnsFALSE
--- that or you could take out theexit;
- and makeshow_error(...)
overridable
解决方案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 }
这篇关于PHP和Codeigniter - 如何检查模型是否存在和/或不会抛出错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!