UPDATE:
Drupal 8 now ships with a PSR-4 autoloader with support for PSR-0 disabled.
See also:
- PSR-4 namespaces and autoloading in Drupal 8
- PHP class autoloading changed to PSR-4 instead of PSR-0
- Drop automatic PSR-0 support for modules
Drupal core now ships with Composer. This means all core- or module-provided classes that follow the PSR-4 standard (excluding the disabled PSR-0 support) will be autoloaded by the system, provided they are placed in the correct directory.
Drupal core uses the following namespaces and directories:
| Namespace | Directory |
|---|---|
Drupal\Core |
core/lib/Drupal/Core/ |
Drupal\Component |
core/lib/Drupal/Component/ |
Modules should place their classes in a modules/$module/src
| Namespace | Directory |
|---|---|
Drupal\comment |
modules/comment/src/ |
Drupal\entity |
modules/entity/src/ |
Drupal\node |
modules/node/src/ |
Drupal\taxonomy |
modules/taxonomy/src/ |
The registry system that is built on top of files[] declarations has been removed, as has hook_registry_files_alter(). All classes provided by module must be converted to PSR-4 and files[] = filename.inc entries can then be removed in the yourmodule.info.yml file.
See Core subsystems converted to PSR-4 standard for more information.
Comments
Namespace convention for module-provided classes
Besides, modules should namespace their classes as
"Drupal\$module_name\..", with optional sub-namespaces.
Module-provided classes that are namespaced this way will be easily found by the autoloader.
For module-provided classes in foreign namespaces, we need a registration or discovery mechanism that has not yet been decided on. (but it will not be the files[] from D7)
classes without module
I have a bunch of classes written for Drupal 7 that I have decided to convert to PSR-0, partly for the exercise and partly for future migration to D8. Do I have to create a module and put these classes (with PSR-0 namespace subdirectories) in in sites/all/modules/my_module/lib? Or should I/can I place the classes in sites/all/vendor or sites/all/libraries? I realise for my D7 site it doesn't really matter, so my question is, what will be the requirement for D8?
Shaun Moss
shaun@astromultimedia.com
https://github.com/mossy2100/
Avoid underscores in class names
The PSR-0 classloader converts underscores in class names into directory separators. As a result:
Saved in file drupalRoot/modules/myModule/lib/myModule/stuff/My_Stuff.php will never load.
The autoloader will instead attempt to find the class at:
drupalRoot/modules/myModule/lib/myModule/stuff/My/Stuff.php
Removing the underscore from the file and class name (MyStuff) avoids the issue.
New doc page for PSR-0 in Drupal core.
See https://drupal.org/node/2156625