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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With