Dynamically Load a Model – CakePHP
Occassionally, I need to load an unrealted model into a controller. There are a number of ways to do this but some are better than others. The following is taken from reply by gwoo to a discussion thread.
App::import() only includes the file. So you would new to create a new instance every time. This is not recommended
ClassRegistry::init() loads the file, adds the instance to the a object map and returns the instance. This is an easy and convenient way to access models.
Controller::loadModel(); Uses ClassRegistry::init() adds the model to a property of the controller and also allows persistModel to be enabled.
While you “can” do any of these things, you should ask yourself why you are creating dependencies on models that are not natural to the controller. If you “have” to do use any of these, then I would do so in reverse order of the way i described them. IE, Controller::loadModel() then CR::init() and actually I never use App::import() for models.






