More shorter way to load models on the fly

This post has been marked as deprecated.

You can use “loadModel” controller method to load models on the fly. For more information of this method please visit http://api.cakephp.org/class/controller#method-ControllerloadModel. Thank you.

In earlier versions of CakePHP we had loadModel function to load model on the fly. There had been other correspondents like loadHelper to load helpers and so on. Later by the coming of 1.2 it turned into App::import(‘Model’, ‘model_name’). By using later App::import() we can load core libraries, controllers, models, helpers, components and behaviors on the fly whenever needed. Following the syntax of import method but in most cases import uses only first two arrangements though:

App::import($type, $name, $parent, $search, $file, $return);

Although we use the same import method to load these classes (models, helpers etc.) they may look to use slightly different approach to construct or create class objects. In fact they simply use the class name as always to create an object. For example to load a model “User” (class name is User) we use:

App::import('Model', 'User'); //loading class file
$User = new User(); //creating object of model User

while to create an object of helper “Html” we use:

App::import('Helper', 'Html');
$Helper = new HtmlHelper();

As I have been using App:import heavily in my controllers to load models on the fly, i always had to write these two lines of code. So why should ‘t i make a single line, i thought. I created the following two lined function, did put it in the app_controller and then called a line of code to load the required model.

Here is the App:import and class object creation:

function loadModel($model)  {
    App::import('Model',$model); //load model..
    $this->{$model} = new $model(); //and create an instance of it
}

and call the following inside the controller:

$this->loadModel('User');

And that’s all! You have “User” class object inside controller action as $this->User now.

3 thoughts on “More shorter way to load models on the fly

  1. As already mentioned, this is already available in the Controller object which does a great deal more work to make sure you get the model you’re looking for. Please use that method as it has much more support.

Leave a Reply