如何检查模型是否存在与CakePHP? [英] How to check if Model exists with CakePHP?

查看:160
本文介绍了如何检查模型是否存在与CakePHP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个通用函数中动态加载模型,我注意到有时我想跳过加载模型,因为它引发了一个404错误。



如何检查如果模型存在?



如下:

  if this-> modelexists($ type){
$ this-> loadModel($ type);
} else {
returnxxx;
}


解决方案

由于您尚未指定版本, CakePHP 1.3



loadModel()方法将返回false,如果它找不到模型,请参阅 API文档。所以只是检查它不会返回假如:

  if(!$ this-> loadModel($ type)){
returnxxx;
}

CakePHP 2.0



如果模型类不存在, loadModel()方法将抛出一个 MissingModelException ,所以只需要捕获它。



API文档



例如:

  try {
$ this-> loadModel
} catch(MissingModelException $ e){
//模型未找到!
echo $ e-> getMessage();
}


I dynamically load models in a general-purpose function and I noticed that sometimes I want to skip loading models because it raises a 404 error.

How can I check if the model exists?

Something like:

if($this->modelexists($type) {
  $this->loadModel($type);
} else {
  return "xxx";
}

解决方案

Since you haven't specified your version, I've split my answer in two, one for 1.3 and one for 2.0.

CakePHP 1.3

The loadModel() method will return false if it cannot find the model, see the API documentation. So just check it doesn't return false like:

if(!$this->loadModel($type)) {
    return "xxx";
}

CakePHP 2.0

If the model class does not exist, the loadModel() method will throw a MissingModelException, so just catch that.

See the API docs on this.

Example:

try {
    $this->loadModel($type);
} catch(MissingModelException $e) {
    // Model not found!
    echo $e->getMessage();
}

这篇关于如何检查模型是否存在与CakePHP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆