Skip to main content

Drupal 8 Namespaces - class aliasing

An article from ComputerMinds - Building with Drupal in the UK since 2005
2nd Aug 2016

Jo Fitzgerald

Developer
Hey, you seem to look at this article a lot! Why not Bookmark this article so you can find it easily in the future?

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 drupal.org.

##Just for fun##
drupal.org 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;

or


use SomeLongDrupallyClass as Bob;

or


use Drupal as ☃;

Hi, thanks for reading

ComputerMinds are the UK’s Drupal specialists with offices in Bristol and Coventry. We offer a range of Drupal services including Consultancy, Development, Training and Support. Whatever your Drupal problem, we can help.