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) {
$this->invertedModels = array_flip(Configure::listObjects('model'));

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.

CakePHP auto-complete in NetBeans

Most annoying thing, while coding projects using CakePHP framework in NetBeans is lack of auto-complete feature for models and components in controllers. You can find some solutions that help avoid this problem like adding to each controller new variables and special phpDoc or adding @property to class phpDoc. In my opinion second option is easier, as it do not require to change code of class itself. So I could add manually this tags to each class. But as a programmer I’m lazy person. So I create this simple tool, which add necessary phpDoc properties to code of each controller, model, component and behavior.
Czytaj dalej CakePHP auto-complete in NetBeans