Drupal Bundle classes

By overridding a given bundle type:

<?php

// modules/opd_presentations/opd_presentations.module

function opd_presentations_entity_bundle_info_alter(array &$bundles): void {
  if (isset($bundles['node'])) {
    $bundles['node'][Presentation::NODE_TYPE]['class'] = Presentation::class;
  }

  if (isset($bundles['paragraph'])) {
    $bundles['paragraph'][Event::PARAGRAPH_TYPE]['class'] = Event::class;
  }
}

I can write my own bundle classes that extend Node, Paragraph, etc, with its own custom methods and behaviour.

<?php

// modules/opd_presentations/src/Presentation.php

declare(strict_types=1);

namespace Drupal\opd_presentations;

use Drupal\paragraphs\Entity\Paragraph;
use Drupal\paragraphs\ParagraphInterface;

final class Event extends Paragraph implements ParagraphInterface {

  public const PARAGRAPH_TYPE = 'event';

  public function getEventDate(): string {
    /** @var non-empty-string */
    return $this->get('field_date')->value;
  }

  public function getEventName(): string {
    /** @var non-empty-string */
    return $this->get('field_event_name')->value;
  }

  public function isPast(): bool {
    return $this->getEventDate() < strtotime('today');
  }

}

Tags