Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Bundle Classes for the Win

Bundle Classes for the Win

Event: DrupalCamp Pune 2023

Drupal 9.3 introduced Bundle Classes. Bundle classes allow us to encapsulate business logic into bundle specific classes. Wonder what are the ways we can use Bundle classes? We will be discussing various types of use cases that we can consider while implementing bundle classes.

In this session we are discussing:

What are the bundle classes
Easy and quick ways to define bundle classes using bca module.
How can we define the methods and use those effectively in twig templates
Impact of bundle classes in the theming
Get computed values from various fields of entity and use it
Write generic methods that are specific to entity’s requirements.
Creating reusable traits to share behaviours across entity-types and projects.

Demo Repository: https://github.com/mohit-rocks/bundle-classes-demo

Mohit Aghera

August 06, 2023

More Decks by Mohit Aghera

Other Decks in Programming


  1. I’m Mohit Aghera Who am I? Today I’ll cover: Drupal

    Developer at PreviousNext. Drupal.org: mohit_aghera Twitter: mohit-rocks • Introduction to Bundle classes • How we can use the bundle classes • Various methods to use the bundle classes
  2. Established in early 2009 to provide full service consulting, design

    and development for large scale Drupal websites. Who is PreviousNext? Successfully delivered many Drupal based projects for Government, Higher Education, Media and Communications clients. Very experienced team with long term staff members. Strong contribution and involvement in the Drupal community.
  3. What are the bundle classes? • Essentially they are business

    objects • Unique class for each entity bundle
  4. How to define Bundle Classes? • Use “bca” contrib module

    • Leverage annotation based discovery
  5. Using methods in Twig & TwigSandboxPolicy • Default allowed method

    prefixes ◦ “get” ◦ “has” ◦ “Is” • Override “twig_sandbox_allowed_prefixes” in settings.php for more
  6. Build abstract classes • Introduce common functionality to abstract base

    classes • Even define generic methods in the abstract class like ◦ getBody ◦ getTags
  7. Generic methods • A few more example of generic methods

    like: • Fetch the file from the media entity • Prepare the array for featured Header • Get the generated image url from the media using image styles • Get taxonomy tags
  8. Traits • Create generic traits that allows reusability • Include

    traits in bundle classes whenever required • https://github.com/dpi/drupal-entity-traits