Drupalwoo ☉

Building a Custom Drupal Event Subscriber for Content Operations

Content operations rarely live in one place. A node is drafted in Brisbane by a freelance writer, reviewed by an editor working out of a Melbourne co-working space, localised for a Hobart audience, then published at a time chosen by a marketing team inside a Sydney agency. Each step raises the same kind of question: what should the site do automatically when this happens?

A module hook answers that question procedurally, and it answers it at a fixed point in the request lifecycle. Drupal's event subscriber API, inherited from the Symfony event dispatcher, lets you listen to those same moments — entity saved, route matched, response about to be sent — from a service you control, that you can autowire, tag with a priority, and unit test in isolation. Recent core releases have moved in this direction, deprecating the older hook_entity_insert(), hook_entity_update() and hook_entity_delete() callbacks in favour of entity events.

That shift suits content operations, where rules accumulate. Embargo windows around public holidays, audit trails for publishing decisions, wording checks against Australian Consumer Law obligations, notifications that must respect consent captured under the Spam Act 2003 — a subscriber gives all of these a single home rather than scattering them across a dozen procedural implementations.

This walkthrough builds a subscriber for an Australian publishing workflow. It assumes Drupal 10 or 11, Composer, and a custom module named aus_content_ops already installed and enabled. No contributed modules are required, and every example runs against core APIs only.

Why an event subscriber fits content operations

Hooks are still fine for small, targeted patches, and they remain the shortest path to many core behaviours. The difference shows up once your logic needs more than a couple of lines: a hook typically reaches for services statically or duplicates logic that another module already wrote. A subscriber is a first-class service, so the container resolves its dependencies, and the same class can be exercised in a unit test with mocked collaborators.

Ordering is the other structural gain. Subscriber methods run according to a priority weight attached to the service tag, so you can guarantee that your embargo check fires before a workflow transition, or that your audit log entry lands after a successful publish. Module weight, by comparison, is a blunt instrument that affects every hook in the module at once.

The skeleton is deliberately small. Extend EventSubscriberBase, write one method per event, and map events to methods in getSubscribedEvents():

<?php

namespace Drupal\aus_content_ops\EventSubscriber;

use Drupal\Core\Entity\EntityInsertEvent;
use Drupal\Core\Entity\EntityUpdateEvent;
use Drupal\Core\EventSubscriber\EventSubscriberBase;

class ContentAuditSubscriber extends EventSubscriberBase {

  public function onEntityInsert(EntityInsertEvent $event): void {
    $entity = $event->getEntity();
    if ($entity->getEntityTypeId() !== 'node') {
      return;
    }

    $this->logger->info('Node created: @title (@bundle)', [
      '@title' => $entity->label(),
      '@bundle' => $entity->bundle(),
    ]);
  }

  public static function getSubscribedEvents(): array {
    return [
      EntityInsertEvent::class => 'onEntityInsert',
      EntityUpdateEvent::class => 'onEntityUpdate',
    ];
  }
}

Two habits carry most of the weight. Return early when the event is irrelevant to your logic, so a subscriber that only cares about nodes does not wake up for every config entity or taxonomy term. And keep each handler focused on one decision, leaving heavier work — sending mail, pushing to a queue, calling an external service — to a dedicated collaborator rather than the subscriber itself.

Registering the subscriber in the service container

The class needs a service definition before the dispatcher will find it. In aus_content_ops.services.yml, autowiring removes the need to list every constructor argument by hand, and the event_subscriber tag registers the class with the event dispatcher pass:

services:
  aus_content_ops.content_audit:
    class: Drupal\aus_content_ops\EventSubscriber\ContentAuditSubscriber
    autowire: true
    tags:
      - { name: event_subscriber, priority: 0 }

The priority attribute on the tag controls execution order relative to other subscribers, including those supplied by modules such as content moderation or redirect. Setting a high number guarantees your handler observes the entity before workflow code rewrites it; setting a low number lets workflow transitions finish first. Choose deliberately rather than by trial and error, because a priority that changes silently when another module is updated is a debugging afternoon you will eventually pay for.

Autowiring works because the constructor type hints map directly onto container services. EntityTypeManagerInterface resolves to the entity type manager, LoggerInterface resolves to the logger channel named after the module, and DateTimeInterface resolves to the site's configured timezone service — which, for a Sydney or Melbourne agency, is usually Australia/Sydney. If a subscriber needs a specific timezone regardless of site configuration, inject the clock service and convert explicitly with DateTimeZone.

Core also exposes hook_event_subscribers(), which lets a module register subscriber classes without a YAML definition. That suits small modules with no dependencies of their own; the YAML route stays clearer when a subscriber needs injected collaborators, and it keeps the class testable in isolation. Whichever route you take, clear the container cache after changing service definitions, since a stale container is the usual reason a subscriber appears to do nothing.

Reacting to node, moderation and workflow events

Entity events are the most useful family for content operations. EntityInsertEvent, EntityUpdateEvent, EntityDeleteEvent and EntityPresaveEvent all expose the entity through getEntity(), and the update event also gives you getOriginalEntity() — the snapshot from before the save. That snapshot is what turns a subscriber into an audit tool: comparing the original and current states tells you exactly what an editor changed.

public function onEntityUpdate(EntityUpdateEvent $event): void {
  $entity = $event->getEntity();
  $original = $event->getOriginalEntity();

  if ($entity->getEntityTypeId() !== 'node' || $original === NULL) {
    return;
  }

  $newly_published = !$original->isPublished() && $entity->isPublished();
  if (!$newly_published) {
    return;
  }

  $this->logger->notice('Published @id by @user', [
    '@id' => $entity->id(),
    '@user' => $this->currentUser->getAccountName(),
  ]);

  $this->state->set('aus_content_ops.last_published', $entity->id());
}

Comparing against the original state matters in practice. Without it, every save of a published node looks like a fresh publication, and your audit trail fills with duplicates within a week of launch.

Content moderation adds a dedicated publish event, available in recent core versions, which fires at the moment an editor approves a moderated item. Subscribe to it and you can stamp approvals with the approving user, the approval time, and the content type — information that later matters when a university in Melbourne or a council in Canberra is asked to evidence its editorial process. Sites without moderation still get EntityUpdateEvent, so write the handler defensively and check $entity->isPublished() rather than assuming a workflow exists.

One limitation is worth remembering early: entity events fire during the save cycle, not inside the request/response exchange. Redirecting an editor from there is unreliable, because there is no response to replace at that point. Redirects belong in a request or response subscriber, while entity events should be used for logging, state changes, queueing and validation.

Using request and response events for editorial rules

Kernel events cover the rest of the lifecycle. KernelEvents::REQUEST fires once per request, KernelEvents::RESPONSE fires once the response is prepared, KernelEvents::VIEW fires as the view is rendered, and KernelEvents::EXCEPTION handles error pages. Together with route subscribers, which extend Drupal\Core\Routing\RouteSubscriberBase and implement alterRoutes(), they let you enforce rules about who reaches a page and when.

A typical Australian use case is a publishing embargo. Many agencies observe core business hours — nine to six, Sydney time — and block non-essential publishing overnight, across weekends, and around public holidays such as Australia Day or ANZAC Day. The check belongs in a request subscriber because it depends on the current time and the current route:

public function onRequest(RequestEvent $event): void {
  if (!$event->isMainRequest()) {
    return;
  }

  if ($event->getRequest()->attributes->get('_route') !== 'node.add') {
    return;
  }

  $sydney = new \DateTimeZone('Australia/Sydney');
  $now = new \DateTimeImmutable('now', $sydney);
  $hour = (int) $now->format('G');

  if ($hour >= 22 || $hour < 6) {
    $event->setResponse(new RedirectResponse('/content-embargo', 302));
  }
}

Because the embargo is expressed in a single named timezone, the same rule behaves predictably for staff in Perth, where the local clock is two hours behind Sydney, and in Adelaide or Darwin, which run on a half-hour offset. An embargo written in server time drifts twice a year when daylight saving begins in October and ends in April — a bug that only appears in the southern spring, and only for some users.

The response subscriber is the right place for anything that must be true of the delivered page. Adding a header, forcing a private cache so embargoed previews are never stored in a shared CDN, or clearing the response before it goes out are all response-level concerns:

public function onResponse(FilterResponseEvent $event): void {
  $response = $event->getResponse();
  if ($response instanceof HtmlResponse) {
    $response->setPrivate();
  }
}

For access rules tied to particular routes, alterRoutes() lets you attach a requirement and pair it with an access checker, which is cleaner than hiding links from the interface. Form-level validation still belongs in a form alter or a custom form class; a subscriber that rewrites submitted values sits too late in the lifecycle to be trusted with anything that matters.

Safeguards, compliance and the wider toolkit

Content operations rules in Australia carry obligations that belong in code, not in a style guide. Under the Spam Act 2003, commercial electronic messages require consent, so any subscriber that triggers an email to an editor or a subscriber list should check the consent state before sending. Australian Consumer Law demands that claims about prices, discounts and end dates be accurate, so a subscriber that publishes a "final days" banner can verify the sale end date against the source before the node goes live. And where a site handles personal information, the Australian Privacy Principles in the Privacy Act 1988 apply to collection, use and disclosure — a subscriber should log decisions without copying personal information into log messages.

Accessibility deserves a specific warning. A subscriber that injects markup into the rendered page can break heading order or landmark structure, which fails WCAG 2.1 AA — a standard that Australian government agencies, universities and many corporate sites are required to meet. Inject content early, in a preprocess or view layer, rather than appending to the final DOM.

Consideration Event subscriber Module hook Custom service with a form Rules or workflow plugin
Trigger points Entity, kernel, route and custom events Fixed procedural callbacks in core Form submit and AJAX callbacks Editor-selected events from configuration
Dependency injection Constructor autowiring from the container Static helpers or manual service calls Full injection, called by your form Configuration driven, limited injection
Ordering Priority weight on the service tag Module weight only Whatever order your code uses Workflow configuration order
Testability Unit test the class with mocked services Kernel tests needed for most hooks Straightforward unit tests Needs a configured workflow to test
Best suited for Cross-cutting content operations rules Small, targeted patches Editor-facing forms and validation Editorial governance and pipelines

The practical takeaway is that a subscriber earns its place once your content operations rules outgrow a single hook. Start with one class, one service definition and one event handler; add complexity when a second rule arrives, and keep the compliance checks close to the code that publishes.