Skip to content
CakePHP

Loading CakePHP Models Inside Other Models and Controllers

2 min read

From time to time in CakePHP 2.x you find yourself needing to load a model that’s not associated with the current model.

There are a few options for loading another model inside a model, but the best as far as I’ve found is to use ClassRegistry::init():-

$AnotherModel = ClassRegistry::init('AnotherModel');

This will load the file for the model, add an instance of the model to the object map and returns the instance. So we can use the model as called above in a model like:-

$data = $AnotherModel->find('list');

With ClassRegistry::init() we can also define the model alias at the same time:-

ClassRegistry::init(array(
    'class' => 'AnotherModel', 
    'alias' => 'AnotherModelAlias'
));

From a controller we can use loadModel():-

$this->loadModel('AnotherModel');

This will use ClassRegistry::init() to load the model and add the model as a property of the controller. So we can use the loaded model like:-

$data = $this->AnotherModel->find('list');

These methods should not be used as a substitute for building relationships between your models and using the associations to work with your models. These are for the rare occassions where you need to access a model that you don’t direct access to.

© 2024 Andy Carter