Skip to content

Instantly share code, notes, and snippets.

@grayside
Created October 20, 2016 04:39
Show Gist options
  • Select an option

  • Save grayside/2edb2cf025b9df8c50db162663c00804 to your computer and use it in GitHub Desktop.

Select an option

Save grayside/2edb2cf025b9df8c50db162663c00804 to your computer and use it in GitHub Desktop.
Identifying a plugin in Drupal 8

A co-worker recently asked me if the following is a good way to identify objects in Drupal 8:

get_class($object) == 'Drupal\Namespace\Thinger\ThingObjectService'

That totally works. It's just not very durable.

In Drupal 8, there is a built-in notion that almost anything might be swapped out for a different behavior. Thinger Service is known to be powered by a given class, but that class can be changed. Plugin X is defined as associated with a given class by annotations and whatnot, but those, too, can have their class changed. This means any code that hardwires a specific class has a slight amount of brittleness.

You might be comfortable with that brittleness, I mean, what are the chances you are going to replace the way text fields work? But it could happen, and when it does, the odds it's done by somewhat that expects your code to "just work" are pretty high.

The object-oriented solution to supporting this kind of swappability is Interfaces, and Drupal is littered with them. Instead of the code snippet above, if you have a viable interface that identifies your thing, you will be more robust with the following:

object instanceof \Drupal\Namespace\Thinger\ThingObjectServiceInterface'

Of course, not everything has an interface, and finding the right interface is sometimes an art in itself.

In the case of plugins and other stuff infused with Drupal's sensibility for embedded metadata, you can often ask for a unique machine identifier associated with the thing.

  • Fields, TypedData, and other Plugin things: getPluginId()
  • Entities: getEntityTypeId(), bundle()

Of course, sometimes you need the specificity of checking a known class. Maybe the goal is in the implementation details. If you find that, you may just have found a leaky abstraction where the design of the class structure has a gap right where you need to move. Do what you need to do.

You will often see specific classes referenced around the Serialization system. Interfaces are often a goal, but not always used. This is a bit unusual in Drupal code, but when you realize the architecture of Serialization is one of the more pure Symfony things surfaced in Drupal, the difference begins to become clear.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment