esn-cy/enum-backed-entity

The ticket booking and management platform of ESN Cyprus.

Maintainers

Package info

github.com/esn-cy/enum_backed_entity

Type:drupal-module

pkg:composer/esn-cy/enum-backed-entity

Statistics

Installs: 0

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v0.1.0 2026-05-24 10:38 UTC

This package is auto-updated.

Last update: 2026-05-25 17:12:29 UTC


README

Enum Backed Entity

A lightweight, zero-boilerplate utility module for Drupal 10/11 that provides a strictly typed, Enum-driven architecture for custom entities.

By abstracting Drupal's FieldDefinition logic into native PHP 8.1+ Enums, this module allows developers to build custom entities with complete type safety, IDE auto-completion, and native fluent builders—without writing massive annotation blocks or repetitive getter/setter methods.

Requirements

  • Drupal ^10 || ^11
  • PHP >= 8.2

Installation

This module can be downloaded via Composer.

composer require esn-cy/enum-backed-entity
drush en enum-backed-entity -y

Quick Start Guide

To use this architecture in your own custom module, ensure your module requires enum_backed_entity in its .info.yml dependencies, then follow these two steps.

1. Define your Fields as an Enum

Create a Backed Enum that implements FieldEnumInterface. This acts as the absolute source of truth for your database schema.

namespace Drupal\example\Entity;

use Drupal\enum_backed_entity\Entity\FieldEnumInterface;

enum ExampleField: string implements FieldEnumInterface 
{
    case Name = 'name';
    case IsApproved = 'approved';

    public function label(): string {
        return match($this) {
            self::Name => 'First Name',
            self::IsApproved => 'Approved',
        };
    }

    public function type(): string {
        return match($this) {
            self::Name => 'string',
            self::IsApproved => 'boolean',
        };
    }

    // ... implement required(), unique(), and settings()
}

2. Create your Entity Class

Extend EnumDrivenEntityBase and tell it which Enum to use. You do not need to write baseFieldDefinitions() as the parent class dynamically builds the schema from your Enum.

namespace Drupal\example\Entity;

/**
 * @ContentEntityType(
 * id = "example_entity",
 * label = @Translation("Example Entity"),
 * base_table = "example_entity",
 * handlers = {
 * "storage" = "Drupal\enum_entity_core\Entity\EnumDrivenEntityStorage",
 * }
 * )
 */
class ExampleEntity extends EnumBackedEntityBase implements ExampleEntityInterface
{
    protected static function getFieldEnumClass(): string 
    {
        return ExampleField::class;
    }
}

3. Usage in your Application

You can now create, query, and modify entities using strict typing and fluent chaining.

// Creation
$entity = ExampleEntity::create()
    ->setValue(ExampleField::Name, 'Jane Doe')
    ->setValue(ExampleField::IsApproved, true);
$entity->save();

// Reading
$name = $entity->getValue(ExampleField::Name);