Can I use one model inside of a different model in CakePHP?

Old thread but I’m going to chime in because I believe the answers to be incomplete and lacking in “why”. CakePHP has three ways to load models. Though only two methods work outside of a Controller, I’ll mention all three. I’m not sure about version availability but this is core stuff so I believe they’ll work.

App::import() only finds and require()s the file and you’ll need to instantiate the class to use it. You can tell import() the type of class, the name and file path details.

ClassRegistry::init() loads the file, adds the instance to the object map and returns the instance. This is the better way to load something because it sets up “Cake” things as would happen if you loaded the class through normal means. You can also set an alias for the class name which I’ve found useful.

Controller::loadModel() uses ClassRegistry::init() as well as adds the Model as a property of the controller. It also allows $persistModel for model caching on future requests. This only works in a Controller and, if that’s your situation, I’d use this method before the others.

Leave a Comment