Early-bootstrap class loading (expert only).
X Autoload has some tricks to enable class loading even before it would be regularly available.
Note: Most of the time, you don't need any of this!
These tricks are for edge cases only. They clutter your code, and they may break in ugly ways if you are using a different version of xautoload.
So, use them only if you are absolutely sure you need them, and only in custom code! Don't do any of this in contrib modules that you want to be used by others!
Early-bootstrap mode / settings.php
Problem: You want to enable autoloading for a library during early bootstrap, before Drupal has loaded the database and modules, and before xautoload would normally start.
Solution: Put this in your settings.php, to have your class loading activated even before Drupal knows about modules:
// Replace the path with the module location of xautoload.
// Note: module_load_include() or drupal_get_path() are not available
// at this point, so we need to hardcode the path.
require_once 'sites/all/modules/contrib/xautoload/xautoload.early.inc';
// Now we can start registering our custom libraries.
// Methods on the class finder are very similar to Composer's ClassFinder.
xautoload()->finder->addPsr4(...);
Regular module namespaces will still only be registered later in the request.
Modules that are not yet completely installed.
Use case #1: Your *.module file contains code that is outside of a function. This code is executed when the *.module file is included. This code directly or indirectly needs classes from the module to be autoloaded.
Use case #2: Your hook_uninstall() contains code that directly or indirectly needs classes from the module to be autoloaded. At the time that hook_uninstall() fires, the module is (naturally) already disabled, so the classes are not registered in xautoload.
Warning: In this case you do not even know if xautoload is enabled or even downloaded!
Solution: Put this in your mymodule.module or mymodule.install:
xautoload()->registerModule(__FILE__);
// Now you can use classes from this module, at the time the file is included.
$obj = new Drupal\mymodule\Foo\Bar();
$obj2 = new mymodule_Abc_Def();
This would not be necessary during normal requests: Usually, the classes are available when a module is included, because xautoload is included first. However, when the *.module file is included during module_enable(), then xautoload does not know about the module yet.
Also note that usually you would not put code outside of a function or class.
Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion