Module Development
Topic

PSR-4 Namespaces and Autoloading in PHP for Drupal 8, 9, and 10

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

Categories
Drupal 8, 9, 10, and 11
More information

Drupal uses PSR-4 namespaces to autoload the correct PHP class from a file, accommodating variations in site structures. 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.

In this tutorial, we'll:

  • Define the PSR-4 namespace standard.
  • Explore its use in Drupal.
  • Learn to read a namespace and locate the corresponding PHP file.

By the end of this tutorial, you should be able to recognize a PSR-4 namespace, determine the related fully-qualified class name, and the location of the corresponding PHP file.

Guides

Not sure where to start? Our guides provide useful learning tracks for all skill levels.

Navigate guides

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.