Dynamic CakePHP models without class definitions

By cbotman

Here’s a nifty CakePHP feature I stumbled across yesterday:

You can use a model without creating a file for it or defining a class for it.

Call a model from your controller or define relationships in other models as normal, and that model can be saved, fetched, recursed, etc, using normal “$this->ModelName->foo()” calls.

Without a model class you wont have any relationships or validation rules defined on the model, but this is still a useful feature.

I often have tables whose only purpose is to populate a drop-down list and/or keep the database normalised. A table of country names, for example.

In the past I would have created a bare-bones class for the model with nothing in it, but now I don’t even have to do that.

I’ve tested this using PHP5 and it works on the latest stable version of CakePHP (1.1) and the 1.2 beta.

I suspect this wouldn’t work for PHP4 though because of the comment that you should declare a model’s name inside its class when using PHP4.

Tags: , , , , ,

Leave a Reply