我正在创建一个我正在使用两个插件的应用程序。 为了将来使用,我想检查两个插件是一起使用还是单独使用。 我需要检查模型是否存在,如果是,则执行某些逻辑,如果不存在 - 不是。 如果我尝试if($ this-> loadModel('Model')){etc} 我得到一个错误,说模型不存在,这是我想要的,但我不想要一个阻止逻辑继续进行的错误。
基本上我想要:
if(Model-> exists()){do-> this} 别的{do-> somethingelse}
我尝试使用php函数class_exists(),但无论模型是否存在,都会返回false。
答案 0 :(得分:1)
我会在2.x时使用App::objects('model')
(不确定何时实施)。
class AppController extents Controller {
private function _modelExists($modelName){
$models = App::objects('model');
return in_array($modelName,$models);
}
}
//Somewhere in your logic
if($this->_modelExists('SomeModel')){
//do model exists logic
} else {
//do other logic
}
*请注意,App::objects('model')
不会包含插件中的模型。你可以这样做:
$models = array_merge(
App::objects('model'),
App::objects('MyPlugin.model')
);
您也可以使用纯php执行此操作,如下所示
if(class_exists('SomeModel')){
//do model exists logic
} else {
//do other logic
}
// The pitfall of this approach, is that it will not assure
// that `SomeModel is a decedent of the `Model` class.
答案 1 :(得分:-1)
你可以这样做:
$model = ClassRegistry::init("User");
如果$ model为null,则表示User模型不存在 您可以从代码中的每个位置
执行此操作