A note on difference between app:import and loadmodel in CakePHP

Posting for, someone searched for terms “cakephp what is the difference between app:import model and loadmodel” and “cakephp what is the difference between app:import and loadmodel” and landed on my blog page but unfortunately i could not provide the answer that time, perhaps. I hope it helps future visitors with similar queries.

Okay, here is the difference. Although the differences has been listed at CakePHP cookbook at cakephp.org here already but i shall try to explain them with the help of short examples.

App::import()

App::import() only includes the file. It does something like we do in include (‘./myfile.php’) and it leaves the rest on you. You can further create an object or use function/methods according to your needs. For example, when you do App::import(‘model’, ‘User’) it includes the user.php model class file and then you do $User = new User() to create an instance of class User which is found in user.php file. As an another example, you do App::import(‘helper’, ‘Time’) and it includes helper class file time.php and you do $time = new TimeHelper() to create an instance of TimeHelper class which is found in time.php file. The first argument passed to import method is the identification mark for the CakePHP internals and is used to identify the location of the requested file. In this example the string ‘model‘ or ‘helper‘ helps it to search the asked file within ‘models‘ or ‘views/helpers‘ directories respectively.

ClassRegistry::init()

ClassRegistry::init() loads the file and adds the instance to an object map and returns the instance. This is an easy and convenient way to access models. It is helpful when you need the model object to be used one time. For example, you can do ClassRegistry::init(“User”)->find(“all”) and forget about the model User further.

Controller::loadModel()

You can use Controller::loadModel() inside your controller actions for multiple use. It is the mostly used and convenient way and of course the most preferred way to include models. It includes the model class file and adds the model instance as a property of the current controller. For example, you are in PostsController and you do $this->loadModel(‘User’) so now you have User object added as $this->User automatically in the scope following this very line which you can use until your controller script processing ends.

Listing them priority-wise one would suggest you to use them in reverse order i.e. from the most preferred to the least preferred like this:
Controller::loadModel()
ClassRegistry::init()
App::import()

And now perhaps you know why. Do you?

Leave a Reply