Skip to content

PHP Architecture

This document describes the core PHP design of Display Builder for contributors and module integrators. For the data formats that this architecture reads and writes, see Internals.

Instance entity

display_builder_instance (src/Entity/Instance.php) is the heart of the module. It stores the working state of a builder session — the source tree, undo/redo history, and profile reference — and exposes the high-level API used by controllers.

Always type-hint against Drupal\display_builder\InstanceInterface.

The instance delegates all tree operations to SourceTree and provides:

  • attachToRoot() / attachToSlot() / moveToRoot() / moveToSlot() / setSource() / setThirdPartySettings() / remove() — tree mutations, each saved as one revision
  • setNewPresent() — sets the whole tree, normalized, as one revision; no save() needed afterwards
  • getSlotNodeIds() — the node IDs of a slot, in order, so a caller never digs into a source plugin's own slot storage
  • getPast() / getFuture() — the revision stack that ApiController::undo() and redo() step through
  • publish() / restore() / revert() — PublishableInterface, the bridge to the permanent storage owned by the buildable plugin
  • getSources() — the present sources tree, nested, as stored in the sources field (SourceTree::getNormalizedStructure() gives the flat view)
  • getPathIndex() — the SourceTree path index cache
  • isPublishedPresent() / getPublicationStatus() — whether there is anything to publish, comparing content hashes that ignore node IDs (Publish button, save status)
  • getHash() / getPublishedHash() — raw draft and published fingerprints, node IDs counted, for the history; the storage alone writes hash, on every save

Source tree cache

The instance builds its SourceTree lazily and keeps it for the language of the object. The cache is dropped in two cases:

  • __clone() — a translation object is a clone, so it must not keep the tree of the object it was cloned from.
  • postSave() — for every translation, since saving can change the sources (UI Patterns adds node IDs to props, and the synchronized sources field cascades structural changes to every translation).

Every mutation ends in a save, so the first read after a change builds a fresh tree. Covered by InstanceTreeCacheTest.

Cardinality

attachToRoot(), attachToSlot(), moveToRoot() and moveToSlot() throw \OutOfRangeException when the target is full: the root against the buildable's getRootCardinality(), a slot against the source's getSlotCardinality() (SDC maxItems for components) through SourceTree::isSlotFull(). ApiController::respondCardinalityFull() turns it into an error message.

Translation

The sources field is translatable with synchronized_translation, so the tree structure is shared and leaf values may differ per translation (DisplayBuildableInterface::isTranslationSynchronized()). InstanceStorage::doPreSave() hashes every translation, and InstanceTranslationSubscriber makes sure the upcast instance has a translation for the request. See Translations.

The tree methods fail one way. An unknown node throws InvalidNodeException, and so does a move into the node itself or one of its descendants. A full root or slot throws \OutOfRangeException. The mutators return the instance, the two attach methods the new node ID, and getNode() returns NULL for a missing node. On the builder's API routes, ApiExceptionSubscriber turns both exceptions into the error toast, so a controller does not catch them call by call.

Revisions are the history

The instance is a revisionable content entity, and every mutator saves one revision per change with its log message, author and timestamp. The default revision is the present; anything below it is the past, anything above it the future.

InstanceStorage owns everything that follows from that, so no controller and no island has to reason about revision IDs:

Method Role
undo() / redo() Move the default revision pointer one step, called from ApiController
getPast() / getFuture() The revisions below and above the pointer
getUsers() Every revision author with their latest timestamp, for the collaboration island
clearFuture() In doPreSave(): a new revision saved from the past drops the future
trimPast() In doPostSave(): keeps at most MAX_HISTORY (20) past revisions

publish() is the deliberate exception: it calls setNewRevision(FALSE), so publishing writes to the permanent storage and stamps the instance without adding a step to the history. restore() and revert() go through setNewPresent() like any other change, and are undoable.

SourceTree — normalized tree engine

src/SourceTree.php stores the tree as three flat maps:

Map Contents
$nodes Raw node data keyed by node ID
$structure Parent/slot relationships keyed by node ID
$root Ordered list of root-level node IDs

This enables O(1) mutations regardless of nesting depth. To locate nodes efficiently, SourceTree maintains a $pathIndex cache, reset on every mutation and rebuilt lazily by getPathIndex().

Critical rules:

  • Moves are ID-based: removeFromCurrentParent() first, then array_splice into the target list. No path is computed before the move.
  • remove() detaches the node with array_splice, then drops its descendants with recursiveRemove().
  • moveToSlot() includes an isDescendant() guard that prevents circular / ancestor moves.

API-first controllers

The UI is powered by a RESTful API defined in display_builder.routing.yml. Controllers are thin entry points — they load the instance, delegate business logic to the instance entity, dispatch an event, and return an HTML partial for HTMX to swap.

ApiControllerBase provides the shared plumbing:

  • dispatchDisplayBuilderEvent(string $event_id, ...) — dispatches the event and returns every island's result as the out-of-band HTMX response; for history, restore and revert it also adds HX-Trigger-After-Settle: display-builder:state-change
  • createEventWithEnabledIsland(string $event_id, ...) — creates the final DisplayBuilderEvent with the triggering island ID and the visible islands, then dispatches it
  • getVisibleIslands() — reads the X-DB-Visible-Islands request header, so islands the client reports as off screen are not rebuilt

The instance itself is a route parameter ({display_builder_instance}), upcast by the entity param converter, never loaded by hand in a controller.

Controllers do not record changes for the real-time collaboration stream: saving the instance does, whoever the writer (Instance::postSave()).

The API surface is split across several controllers rather than one:

Controller Responsibility
ApiController attach to root/slot (also moves and preset drops), get, reload island, update, third-party settings, undo, redo
ApiActionsController paste (also duplicate), delete, save as preset, paste and delete styles
ApiPublishingController publish, restore, revert
ApiPreviewController component, block and preset library previews; the preview page, over the Builder or in a tab (getDisplayPreview(), route display_builder.preview_island)
ApiSseController server-sent events for real-time collaboration

Never put business logic in controllers. Mutations belong in InstanceInterface methods; side effects belong in event subscribers.

Event system

After every tree mutation, the controller dispatches a Symfony event. The event then fans out to every enabled island plugin so each can update itself via HTMX out-of-band swaps.

Event names and island methods

Every constant in DisplayBuilderEvents holds a name prefixed with the module, as core event names are. DisplayBuilderEventsSubscriber maps each one to the island method of the same meaning:

const ON_PUBLISH = 'display_builder.publish';
// DisplayBuilderEvents::ON_PUBLISH => 'onPublish'

A subscriber uses the constant, never its value.

Island plugin system

Islands are Drupal plugins (src/Plugin/display_builder/Island/) annotated with #[Island(...)]. All island layer code lives in src/Island/.

Reload traits

Every island event is a method of the single IslandEventSubscriberInterface (11 methods). IslandPluginBase no-ops all of them, so an island overrides only what it answers. Three traits answer the common groups with a full reload through reloadWithGlobalData(), provided by IslandPluginBase:

Trait Covers
IslandStructureReloadTrait onAttachToRoot, onAttachToSlot, onMove, onUpdate, onDelete
IslandLifecycleReloadTrait onHistoryChange, onRestore, onRevert
IslandReloadEventsTrait Both of the above — convenience aggregate

Not covered by any trait, so an island that needs them overrides directly: onActive, onPublish, onPresetSave.

Deferred islands

The triggering island is never rebuilt. An island whose isDeferrable() returns TRUE is also skipped while off screen (DisplayBuilderEventsSubscriber::shouldDefer()); the client asks for it again through display_builder.api_island_reload, answered by the island's reload().

DisplayBuildable integration pattern

External integrations (entity view, entity view override, page layout, Views, pattern preset) implement DisplayBuildableInterface. EntityView, PageLayout, ViewDisplay and PatternPreset (in display_builder_ui) extend ConfigBuildablePluginBase; EntityViewOverride extends DisplayBuildablePluginBase and implements DisplayBuildableOverrideInterface. This separates builder logic from storage backends.

When working in integration submodules, always follow this chain:

getInstanceId() → getInstance() → getSources() → publish()

Never access the instance entity storage directly in integration code, except to list instances.

A new buildable plugin is discovered by both listings, with different needs:

  • The admin instances list is a View of instance storage. Every instance of the plugin is listed with no code. One whose getProfile() returns no profile shows no operation. Create the instance when Display Builder is enabled on a display, as page layouts, entity view displays and views do, so a display enabled by a config import is listed too.
  • The Instances panel lists the plugin's displays only once it overrides collectDisplays(), which returns none in the base class. Override collectDisplaysBound() too, and toUrl() for its collection and add-form links, for the group heading.

Top bar item

src/Plugin/TopBarItem/DisplayTopBarItem.php lists, in the Navigation top bar of front-end pages, the displays that built the page. Modules add theirs with hook_display_builder_page_displays() (see display_builder.api.php).