PHP和Codeigniter - 如何检查模型是否存在和/或不抛出错误? [英] PHP and Codeigniter - How do you check if a model exists and/or not throw an error?
问题描述
示例1
bschaeffer的
回答这个问题 - 在他的最后一个例子:
$ this-> load-> model('table');
$ data = $ this-> table-> some_func();
$ this-> load-> view('view',$ data);
'table'
不存在?
示例#2
try {
$ this-> load-> model('serve_'。$ model_name,'my_model');
$ this-> my_model-> my_fcn($ prams);
//模型存在
} catch(Exception $ 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;
...不冷却...所以我overrode: model(...)
- > my_model(..)
(如果你只是覆盖它会收到错误),并删除 show_error(...)
你不能覆盖它 - 奇怪的Codeigniter)。然后在 my_model(...)
中引发异常
我的个人意见:调用函数 return
show_error(message);
其中show_error返回 FALSE ---或
你可以取出退出;
- 并使 show_error(...) / code>
overridable
解决方案
$ 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 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
解决方案 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屋!