我正在创建一个应用程序,其中使用两个插件。 为了将来使用,我想检查这两个插件是一起使用还是单独使用。 我需要检查模型是否存在,如果存在,则执行一些逻辑,如果不存在,则不执行。 如果我尝试 if($this->loadModel('Model')) { etc } 我收到一条错误消息,指出模型不存在,这正是我想要的,但我不希望出现阻止逻辑继续进行的错误。
基本上我想要:
if(模型->exists()) { do->this } else { 做->别的事 }
我尝试使用 php 函数 class_exists() 但无论模型是否存在都会返回 false。
从 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.
你可以这样做:
$model = ClassRegistry::init("User");
如果 $model 为 null 这意味着用户模型不存在 您可以从代码中的任何位置执行此操作