Juan Carlos Orrego
2 min readJun 13, 2022

Entity Bundle Classes

From Drupal 9.3.0 and up, it’s possible to define a custom class for basically any entity and / or bundle.

This may not seem very useful at first, but once you have a site that has been growing for a while, and multiple bundles has been created, and many custom modules and many hooks in there, it starts to make the benefits of having classes in this more specific entities, pretty clear.

I will start with a simple case that may sound familiar to many.

We can easily grasp the simplicity and advantages of the taxonomies in Drupal, so in my case it’s a pretty common pattern to use, when defining the architecture of a new project, to store many pieces of content there. But in that process as soon as you grasp some specific behavior is needed, pre/post processing, or maybe many fields needs to be added to a specific vocabulary, deriving in possibly many hooks and conditions in your code, the most common approach is to create a custom entity instead.

But, what if we can provide many (if not all) of the benefits of a custom entity, still using the taxonomy content? Well, thats what entity bundles classes are up to.

And it’s actually pretty simple to start using them.

In previous Drupal versions, this can be accomplished with the discoverable_entity_bundle_classes module: Discoverable Entity Bundle Classes. This module provides classes for bundles of custom entities, using specific annotations, but have some limitations like the previous example when we want to modify the associated class of a vocabulary term.

Now this is included in Drupal core, and the way to define the classes its using a hook call inside your custom module:

function mymodule_entity_bundle_info_alter(array &$bundles)) {
if (isset($bundles['node']['page'])) {
$bundles['node']['page']['class'] = BasicPage::class;
}
}

I won’t repeat all the good examples found out there, just point out that using this classes with all the possibilities of interfaces, traits, dependency injection, and testing, makes your project code more maintainable.

Drupal change record page: Introducing bundle classes.

Another useful article: Drupal 9: Entity Bundle Classes .

Juan Carlos Orrego
0 Followers

Developer, heavy user of: Laravel, VueJS, Drupal, TailwindCSS, AWS…