Register additional locations with hook_xautoload()
Last updated on
30 April 2025
hook_xautoload() allows to register additional locations and patterns for class loading, beyond those registered by default.
hook_xautoload() takes an $adapter argument, which is documented here:
http://cgit.drupalcode.org/xautoload/tree/src/Adapter/LocalDirectoryAdap...
/**
* Implements hook_xautoload()
*
* Register additional classes, namespaces, autoload patterns, that are not
* already registered by default.
*
* @param \Drupal\xautoload\Adapter\LocalDirectoryAdapter $adapter
* An adapter object that can register stuff into the class loader.
*/
function hook_xautoload($adapter) {
// Register a namespace with PSR-0.
$adapter->add(
// Namespace of a 3rd party package included in the module directory.
'Acme\GardenKit\\',
// Path to the 3rd party package, relative to the module directory.
'shrubbery/lib');
// Register a namespace with PSR-4.
$adapter->absolute()->addPsr4(
// The namespace.
'Acme\ShrubGardens\\',
// Absolute path to the PSR-4 base directory.
'/home/karnouffle/php/shrub-gardens/src');
// Scan sites/all/vendor/composer for Composer-generated autoload files, e.g.
// 'sites/all/vendor/composer/autoload_namespaces.php', etc.
$adapter->absolute()->composerDir('sites/all/vendor/composer');
}
hook_xautoload() fires quite early in the request (though after hook_boot(), to allow non-bootstrap modules to participate). It also fires when new modules were enabled.
Another fun thing: hook_xautoload() does not fire in every request. It only fires if one of the classes is not in the APC cache. This way, it is totally skipped on the average request, saving you yet another few milliseconds.
Help improve this page
Page status: Not set
You can:
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