Models autoloading in CakePHP

CakePHP convention require to declare in each controller which model we want to use in it by declaring $uses array.

$uses = array('Model1', 'Model2');

In some of my projects, list of models required by some controllers, became bigger and bigger. So eventually they include most models from that project, and part of them was used only in some specific cases, like error handling. Instead of adding all required models to $uses array, I could import some of them explicit when they are needed using:

App::import('Model', 'ModelName');
$this->ModelName = new ModelName();

But there is another option: I could write some code that will auto load required models, when they are needed.

You have to add below function to your AppController to make it work:

public function &__get($name) {
if(!isset($this->invertedModels)){
$this->invertedModels = array_flip(Configure::listObjects('model'));
}

if(isset($this->invertedModels[$name])){
$this->loadModel($name);
return $this->$name;
}
}

How does it work?
It is using one of PHP 5 magic functions – __get(). This functions is used when you try to access some nonexistent property in class. So if you add this code, and then you will try to access some undefined model in code, PHP will try to create this model then.

In similar way you can achieve components auto loading. But there could be one more thing needed. I will write about it soon.