PHP namespaces provide a way to group related classes, interfaces, functions and constants. This helps keep code organized, and prevents naming conflicts between your code and Drupal core or another module's code. Autoloading in PHP is any mechanism for automatically including required class files on demand. And PSR-4 Autoloading is a specific method for mapping a fully qualified namespace and class name to a file path.
Drupal uses the PSR-4 standard to autoload the correct PHP class from a file, accommodating variations in the exact location of files, and making the large code base more manageable. As a module developer, it's important to understand PSR-4, as it dictates the location within your module directory for most of your custom code.
Example tasks
- Recognize a PSR-4 namespace
- Determine the related fully-qualified class name
- Find the corresponding PHP file given a namespace
Confidence
Namespaces are defined in the PHP-FIG standard, PSR-4: Autoloader. This PSR-4: Autoloader standard is stable, isn't likely to change anytime soon, and has been used in Drupal since Drupal 8.
Drupalize.Me resources
External resources
-
PHP Namespaces in Under 5 Minutes (symfonycasts.com)
- This screencast from SymfonyCasts explains PHP namespaces.
-
PHP Manual: Namespaces (php.net)
- This is the PHP Manual's guide to namespaces.
-
PSR-4: Autoloader (php-fig.org)
- This PSR describes a specification for autoloading classes from file paths. It is fully interoperable, and can be used in addition to any other autoloading specification, including PSR-0. This PSR also describes where to place files that will be autoloaded according to the specification.
-
PSR-4 namespaces and autoloading in Drupal (Drupal.org)
- The Drupal Wiki documentation describing PSR-4 namespaces and autoloading in Drupal.