tags:

views:

63

answers:

2

I am writing a add-on module which is integrated with an existing PHP application; Because I am using a MVC pattern, and which may requires lot of inclusion of classes (which might not be used at all depending on the action of the user), I decide to use autoloading of classes.

However, I have to ensure that the autoload function does not interferes with the normal operations of the existing applications.

  1. Does autoload only kicks in if a class name is not defined?

  2. Say I have to write another module which uses its own autoload functions (say, I have an autoload for a module, since they each reside in their own folder), how do I differentiate which module is it for?

For #2, I thought of 2 options. Either prefix the class name with the module name (Such as 'MyNewModule_View_Default' and 'AnotherModule_View_Default'), or use file_exists to check the include file exists.

Other suggestions are welcomed too!

A: 
  1. Yes, autoloader is only called when class name is not found.

  2. Usually you'd check the class' namespace (pre 5.3 you use pseudo-namespaces, usually separated by an underscore). So your autoloader would only load classes that are under the namespace(s) of your application.

reko_t
+5  A: 
  1. Just check if the class that is to be loaded already exists with class_exists() before actually loading it in your autoloader implementation. Especially if you have multiple registered autoloaders (see 2).

  2. You can specify multiple autoloaders in a stack via spl_autoload_register(). The registered functions are executed in the order in which they where registered until the class is successfully loaded. You can specify different autoloaders for different modules for example. Or you can do a namespacing approach like in the Zend_Framework, if you have control over class names.

Techpriester
The autoloader will only be called if the class doesn't exist, so point number one is not a problem.Point number two is vital; always use spl_autoload_register() instead, as other libraries that you use may well use this as well (and registering any function with spl_autoload_register() causes PHP to ignore any __autoload() function you define anyway).
El Yobo
It might not be necessary in most scenarios but if you have complex autoloaders, calling class_exists() before actually loading a class can prevent some headache.
Techpriester
Actually, you're right; I can imagine some ways in which that could happen! If your autoloader loads more than one class (either directly or indirectly, by triggering another autoloader call) then a class which did not exist at the time the autoloader was called could exist before you try to require() the class file. Thankfully that hasn't happened to me, but I'll bear that in mind now :)
El Yobo