Question

How does Drupal handle autoloading of classes through modules? For instance, if I have an Events module, and I declare a class called Event, and then in the .info file I include the class file, how is this registered?

The problem is that I'm trying to dynamically get an array containing all loaded class names. get_declared_classes() does not return the names of all my classes declared in this manner, so I'm assuming that they're autoloaded somehow. Following the suggestions from another stack overflow question, I tried getting all of them with spl_autoload_functions(), but that was also unsuccessful.

Any ideas?

Was it helpful?

Solution

All files listed in .info files are parsed when modules are rebuild (Only changed/new files in that list are, for performance reasons).

That information is then stored in the {registry} and {registry_files} tables. So if you want to get all classes or those according to a given naming pattern, you can query those tables.

OTHER TIPS

Drupal maintains a code registry and uses it for its classes autoloader. To populate this registry with your module's classes, you should add their files to the files[] entry in it's .info file:

files[] = includes/Foo.inc
files[] = includes/Bar.inc

PHP's class autoloading will make sure that the parent class file is also loaded.

Credit to user pier-buyle for this answer, see his original answer here for the same question.

Hope that helps

spl_autoload_functions() returns the list of the autoload functions that have been registered with spl_autoload_register(). Drupal registers two autoload functions: one for the classes (drupal_autoload_class()), and one for the interfaces (drupal_autoload_interface()).

Both the functions use _registry_check_code(); using its code, you can write a function that lists all the classes implemented by Drupal 7 modules.

If you have added an entry to the files[] array of the .info file, you will have to go to your modules administration section and click on "save configuration". This will get drupal to refresh the .info information, and the new entries will be registered.

I have found that declaring my include files in the info file does not get them recognized when I start running the module. If I have a class Event in the file event.inc. but crate an object in the module, it is not recognized. I add the line

include_once ('CMatArticleHandler.inc');

prior to the $variable = new event(); line. Im' new at this so there may be more to it then this, but it has worked so far.

Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top