Namespaces

Concept of namespaces is introduced with Drupal8. Namespaces are one of the most significant changes in PHP 5.3. As the size of your PHP code library increases, the more likely you will accidentally reuse a function or class name that has been declared before. Name collision problems can be solved with namespaces. PHP constants, classes, and functions can be grouped into namespaced libraries. Namespaced code is defined using a single namespace keyword at the top of your PHP file. It must be the first command. PHP allows you to define a hierarchy of namespace names so libraries can be sub-divided. Sub-namespaces are separated using a backslash () character.

Some rules to follow when using namespaces in code are -

  • Classes and interfaces with a backslash \ inside their fully-qualified name (for example: Drupal\simpletest\WebTestBase) must not use their fully-qualified name inside the code.
  • Classes and interfaces without a backslash \ inside their fully-qualified name (for example, the built-in PHP Exception class) must be fully qualified when used in a namespaced file.
  • n a file that does not declare a namespace (and is therefore in the global namespace), classes in any namespace other than global must be specified with a "use" statement at the top of the file.
  • When importing a class with "use", do not include a leading .
  • When specifying a class name in a string, use its full name including namespace, without leading .
  • Specify a single class per use statement.
  • If there are more than one classes to 'use', there is no specific rule to order them.
  • PHP allows classes to be aliased when they are imported into a namespace. In general that should only be done
  • to avoid a name collision. If a collision happens, alias both colliding classes by prefixing the next higher portion of the namespace.
  • Custom modules creating classes should place their code inside a custom namespace.
Drupal\<module name>\...

Drupal 8 supports PSR-4, so to permit class autodiscovery, a class in the folder:

<module folder>/src/SubFolder1/SubFolder2

should declare the namespace:

Drupal\<module name>\SubFolder1\SubFolder2

Note that the /src/ subfolder is omitted from the namespace.