Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if Model exists with CakePHP?

Tags:

php

cakephp

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";
}
like image 300
Chobeat Avatar asked Dec 09 '22 02:12

Chobeat


2 Answers

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();
}
like image 197
Oldskool Avatar answered Dec 23 '22 12:12

Oldskool


CakePHP 2.x

function model_exists($type){
  $model_list = array_flip(App::objects('model'));
  return isset($model_list[$type]);
}

You can add this to AppController and use in combination with &__get() to auto-load the model if you like. In that case you may want to use a member variable (e.g. $this->model_list) to save the list so you don't have to call App::objects() each time.

like image 23
Adam Albright Avatar answered Dec 23 '22 14:12

Adam Albright