Decorating a core service without patching

· 5 min read

Sooner or later, a Drupal project needs to change the behaviour of a core or contrib service: enrich autocomplete results, log around an HTTP call, change a path resolution rule… The usual reflexes are a patch (fragile on every update) or replacing the class (which clashes with the first module that does the same thing).

Drupal is built on Symfony’s service container, which offers a better option: decoration. This article shows how to use it properly and how to avoid its traps.

The idea

A decorator is a service that takes the place of another service while receiving the original as an argument. Every consumer gets the decorator without knowing it, and the decorator delegates to the original whatever it doesn’t want to change.

Before:   consumer ──> original service
After:    consumer ──> decorator ──> original service (.inner)

Unlike replacing the class, several decorators can stack on the same service: each one wraps the previous one.

A real case: enriching entity autocomplete

On a site with many content items sharing the same title, editors can’t tell which “Annual report” to pick in a reference field. We want to show the content type next to the title, for every reference field, without touching the widget.

The service in charge is entity.autocomplete_matcher, which implements EntityAutocompleteMatcherInterface.

Declaring the decorator

# my_module.services.yml
services:
  my_module.entity_autocomplete_matcher:
    class: Drupal\my_module\Entity\BundleAwareAutocompleteMatcher
    decorates: entity.autocomplete_matcher
    arguments: ['@.inner', '@entity_type.manager']

@.inner refers to the decorated service (the short syntax is available since Symfony 5.1, and Drupal 10 runs on Symfony 6). On older projects you will see the long form @my_module.entity_autocomplete_matcher.inner.

Implementing the decorator

<?php

namespace Drupal\my_module\Entity;

use Drupal\Component\Utility\Html;
use Drupal\Core\Entity\Element\EntityAutocomplete;
use Drupal\Core\Entity\EntityAutocompleteMatcherInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;

final class BundleAwareAutocompleteMatcher implements EntityAutocompleteMatcherInterface {

  public function __construct(
    private readonly EntityAutocompleteMatcherInterface $inner,
    private readonly EntityTypeManagerInterface $entityTypeManager,
  ) {}

  public function getMatches($target_type, $selection_handler, $selection_settings, $string = '') {
    $matches = $this->inner->getMatches($target_type, $selection_handler, $selection_settings, $string);
    if ($target_type !== 'node' || !$matches) {
      return $matches;
    }

    $ids = array_map(
      fn (array $match) => EntityAutocomplete::extractEntityIdFromAutocompleteInput($match['value']),
      $matches
    );
    $nodes = $this->entityTypeManager->getStorage('node')->loadMultiple(array_filter($ids));
    $bundles = $this->entityTypeManager->getStorage('node_type')->loadMultiple();

    foreach ($matches as $i => $match) {
      $node = $nodes[$ids[$i]] ?? NULL;
      if ($node && isset($bundles[$node->bundle()])) {
        $matches[$i]['label'] .= ' <small>(' . Html::escape($bundles[$node->bundle()]->label()) . ')</small>';
      }
    }
    return $matches;
  }

}

One drush cr, and every reference field on the site shows the content type. No core class was modified, and the next Drupal update won’t change that.

The label of an autocomplete match is HTML already escaped by the original matcher, so we only escape what we add.

Decorator order: decoration_priority

When several modules decorate the same service, the order is set with decoration_priority (0 by default). The higher the priority, the earlier the decorator is applied, so the closer it sits to the original service:

services:
  module_a.matcher:
    decorates: entity.autocomplete_matcher
    decoration_priority: 10
  module_b.matcher:
    decorates: entity.autocomplete_matcher
    decoration_priority: 1

Result: module_b.matcher(module_a.matcher(original)). The consumer calls module_b first.

To decorate a service that only exists when an optional module is enabled, add decoration_on_invalid: ignore: the decorator is then simply dropped when the decorated service is missing, instead of breaking the container rebuild.

The alternatives, and when to prefer them

ServiceProvider: altering a definition

A {ModuleName}ServiceProvider class (CamelCase, at the root of the module namespace) is discovered automatically. Its alter() method can change any definition:

<?php

namespace Drupal\my_module;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

final class MyModuleServiceProvider extends ServiceProviderBase {

  public function alter(ContainerBuilder $container) {
    if ($container->hasDefinition('some.service')) {
      $container->getDefinition('some.service')
        ->setArgument(2, '%my_module.custom_ttl%');
    }
  }

}

It is the right tool to change an argument, a tag or a parameter. Used for a setClass(), it becomes a class replacement, with the “last module wins” problem: if two modules replace the same class, one of them is silently ignored.

The same provider’s register() method can register services conditionally, for example only when a module is enabled ($container->getParameter('container.modules')).

Compiler pass: acting on the whole container

To collect every service carrying a tag, or transform many definitions at once, register a compiler pass from register():

public function register(ContainerBuilder $container) {
  $container->addCompilerPass(new ReportGeneratorPass());
}

Powerful, but rarely needed in an application module. For simply collecting tagged services, Drupal already provides the service_collector tag.

Decision table

Need Tool
React to an event, alter data Hook or event subscriber
Replace a plugin hook_*_info_alter()
Change a service argument or parameter ServiceProvider::alter()
Change a service’s behaviour while staying compatible with other modules Decoration
Act on many services at once Compiler pass

The traps

1. A consumer type-hints the concrete class

Decoration only works if every consumer depends on the interface. If a module type-hints its constructor on the concrete class (EntityAutocompleteMatcher $matcher), your decorator causes a TypeError on the first call. Check before decorating:

grep -rn "EntityAutocompleteMatcher \$" web/core web/modules/contrib

If the service has no interface, the only way out is to extend the original class in the decorator, and you lose clean stacking.

2. Forgetting an interface method

The decorator must implement every method of the interface and delegate the ones it doesn’t change. The day the interface gains a method (it happens between minor versions), your decorator has to follow. A Kernel test is enough to catch it.

3. Stateful services

If the original service exposes setters or keeps internal state (setX() then getY()), delegate every call to $this->inner. A decorator that keeps its own copy of the state produces bugs that are very hard to track down.

4. The container cache

Service definitions are compiled and cached. After any change to a services.yml or a ServiceProvider, a drush cr is mandatory. During deployment, drush deploy already takes care of it.

Testing the decorator

A Kernel test checks both the registration and the behaviour:

public function testDecoratorIsRegistered(): void {
  $matcher = $this->container->get('entity.autocomplete_matcher');
  $this->assertInstanceOf(BundleAwareAutocompleteMatcher::class, $matcher);
}

If another module decorates the same service with a lower priority, this test fails. That’s intended: it documents the expected order.

Conclusion

Decoration is the cleanest way to change a service’s behaviour in Drupal: no patch to maintain, no clash with other modules, and a readable intent in services.yml. The rule to remember: decorate to change behaviour, alter() to change configuration, and use hooks and events whenever they exist.

Next in this series →Inbound and Outbound Processing in Drupal: Principles and Examples