Monday, October 24, 2011

CakePHP 2.0 : Autoloading Classes

The CakePHP 2.0 migration guide talks a lot about autoloading of classes.  For users of CakePHP, not much as changed.  There are just some new rules to follow when dealing with loaded classes.

Here are some guidelines that I'll be following:

  • When dealing with models in a controller, use $this->loadModel().  This should be nothing new.  If you're in a component, and have a reference to the operating controller, then $this->Controller->loadModel() will be more your style.
  • When dealing with models everywhere else, use ClassRegistry::init().  In fact, unless you need to load the model in to your current instance, $MyModel = ClassRegistry::init('MyModel') should be the usage.
  • When referencing a class, use App::uses().  Let us say that you have a model that needs to access a library that is going to do some REST, RPC or SOAP calls for you.  Before the class definition, you might have App::uses('MyRPCLib','Lib');  and in the code, you need $MyRPC = new MyRPCLib();  Autoloading only loads the class, it does not instantiate it.
  • When referencing a file that does not have classes, use App::import().  Usually used for Vendor files containing functions.
If you're finicky, you might also have App::uses('ClassRegistry','Utility'); at the top of any file using the ClassRegistry class.  However, if your application has any models defined, then chances are, ClassRegistry has already been loaded, as a part of the Model class.

It is highly recommended to have App::uses('ClassRegistry','Utility') at the top of any file using the ClassRegistry class.  In fact, it's highly recommended to have an App::uses() statement for any class that has not been previously seen in any given file.  This becomes relevant when you are setting up tests, and your component tests don't know where to load the Component class from.

No comments:

Post a Comment