【问题标题】:Cakephp check if model existsCakephp 检查模型是否存在
【发布时间】:2011-06-29 08:32:23
【问题描述】:

我正在创建一个使用两个插件的应用程序。 为了将来的使用,我想检查这两个插件是一起使用还是单独使用。 我需要检查模型是否存在,如果存在则执行一些逻辑,如果不存在 - 不存在。 如果我尝试 if($this->loadModel('Model')) { etc } 我收到一条错误消息,说我想要的模型不存在,但我不希望出现阻止逻辑继续进行的错误。

基本上我想要:

if(Model->exists()) { do->this } 其他 { 做->其他事情 }

我尝试使用 php 函数 class_exists() 但无论模型是否存在都会返回 false。

【问题讨论】:

    标签: cakephp model exists


    【解决方案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.
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      $model = ClassRegistry::init("User");
      

      如果 $model 为 null 这意味着用户模型不存在 您可以从代码中的任何位置执行此操作

      【讨论】:

      • 实际上它永远不会为空!如果找不到该类,则为 AppModel。您需要检查 App::import() ,它返回成功的布尔值
      • 错了,这个初始化了一个新类,无论如何它与你声明的模型不匹配
      • mark 的评论是正确的。另外,请参阅stackoverflow.com/questions/9382631/… 以获得更详细的答案。
      猜你喜欢
      • 1970-01-01
      • 2016-11-30
      • 2017-12-21
      • 2012-08-13
      • 2014-07-17
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多