Author image

Drupal 8 Namespaces - class aliasing

Class Aliasing is the simple, but very useful solution to the problem of needing two classes (from different namespaces) with the same name.

The problem

I recently found myself in a similar situation and my thanks go to Ben Doherty (benjy) for introducing me to the solution.

While creating the Drupal 7 version of the Link field MigrateCckField plugin, I realised that a lot of code could be reused from the existing Drupal 6 version. Both the existing Drupal 6 class and the new Drupal 7 class extending it would need to be called LinkField, but how could this be achieved? Obviously this would not work:

use Drupal\link\Plugin\migrate\cckfield\d6\Linkfield;

class LinkField extends LinkField {

The solution

To make this snippet work, the existing LinkField class needs to be known by a different name - it requires an alias. The convention demands that the alias be formed by prefixing the class name (LinkField) with the next higher portion of the namespace (d6). In this case the alias becomes D6LinkField (after the necessary capitalisation).

Thus the correct form of the previous snippet is:

use Drupal\link\Plugin\migrate\cckfield\d6\Linkfield as D6LinkField;

class LinkField extends D6LinkField {

Very simple, but ever so useful.

Further reading

For additional clarification, I recommend you review the straightforward example of Class Aliasing in the Namespace article on

Just for fun clearly states:

"Aliasing should only be done to avoid name collisions."

But that didn't stop us having some fun in the ComputerMinds office, how about these possible uses of Class Aliasing:

use Drupal as YourMum;


use SomeLongDrupallyClass as Bob;


use Drupal as ☃;