Take the 2-minute tour ×
Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

I seem to remember some autoloading functionality for classes in d7. Is there any documentation on this?

  • How should one organise the files containing the classes?
  • How can one make sure that parent-classes are loaded on instantiating a child-class?

I would like to avoid writing an autoloader for each module that has Classes.

share|improve this question

2 Answers 2

up vote 8 down vote accepted

Drupal 7 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.

share|improve this answer

Yep, Pierre is correct.
Besides that, you can use xautoload module to abbreviate your info file with wildcards.
Doc page: http://drupal.org/node/1976198

Syntax:

files[] = includes/*.inc

And besides that, you can attempt to be forward-compatible with Drupal 8, and use PSR-0 for your modules. This is also supported by xautoload.

Namespace and class: \Drupal\my_module\OptionalSubNamespace\MyClass
File: (module dir)/lib/Drupal/my_module/OptionalSubNamespace/MyClass.php

Doing this will make the files[] stuff obsolete.

share|improve this answer
    
If you use xautoload, then you can follow PSR-0 and starts using Drupal 8 class and namespace naming conventions and autoloader behavior. –  Pierre Buyle Aug 21 '13 at 14:49
    
that's what i'm saying, isn't it :) –  donquixote Aug 21 '13 at 15:07
    
is it possible to autoload a class found in a subfolder with xautoload? e.g. in my hook_entity_info, i added 'controller class' => 'Drupal\myentity\controller\MyEntityController' I have put my class in modules/myentity/lib/Drupal/controller/MyEntityController.php but I get an error the controller class could not be loaded. –  yeahman Mar 31 at 17:34
    
Hi yeahman, can you get on irc #drupal? –  donquixote Mar 31 at 17:34
    
@yeahman Fact is, I used the scenario you mention a dozen of times. I imagine you simply have a bug in your code.. we can examine on irc. –  donquixote Mar 31 at 17:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.