
If you have ever built a custom block in Drupal, you have written a plugin. A field formatter, a text filter, a migration process plugin or a Views handler: plugins too. It is probably the most used extension mechanism in core, and yet many developers use it by copy-paste without really knowing what happens under the hood.
This article starts from scratch: what the plugin system is for, how Drupal finds your classes, how to create a plugin of an existing type, and then how to define your own plugin type. All examples use current Drupal 11 syntax (PHP attributes) and were checked against the Drupal 11.3 core code.
The problem the Plugin API solves
Picture a module that sends notifications: by email today, on Slack tomorrow, maybe by SMS later. Three needs show up:
- Several interchangeable implementations of the same contract (“send a notification”).
- Automatic discovery: another module must be able to add a channel (Teams, webhook…) without changing yours.
- Metadata you can use without instantiating the class: a label for a select list, a description for the admin UI.
A plain service doesn’t tick these boxes: only one implementation is active at a time. Neither does a hook: no interface contract, no per-instance configuration. This is exactly what the Plugin API provides.
A plugin is a small interchangeable class, implementing a shared interface, discovered automatically by Drupal and described by metadata.
Vocabulary
Five notions are enough to understand everything.
| Notion | Role | Example for blocks |
|---|---|---|
| Plugin type | The contract: an interface and a folder convention | Blocks: BlockPluginInterface, folder src/Plugin/Block |
| Definition | A plugin’s metadata, read without instantiating it | id, admin_label, category |
| Discovery | The mechanism that finds definitions | Reading the #[Block(...)] attributes |
| Plugin manager | The service that discovers, caches and instantiates | plugin.manager.block |
| Instance | A plugin object with its own configuration | The “Latest articles” block placed in the sidebar, set to 5 items |
The key point: one class can produce several instances, each with its own configuration. Place the same block twice in two regions with different settings: one class, two instances.
How Drupal finds your plugins
When you call getDefinitions() on a plugin manager:
- The manager scans the agreed subfolder (
src/Plugin/Blockfor blocks) in every enabled module, based on the PSR-4 namespaces. - It reads the PHP attribute of each class it finds (
#[Block(...)]) and builds the definition from it. - It runs the derivers (more on those below), which can turn one definition into several.
- It invokes an alter hook (
hook_block_alter()) so other modules can change the definitions. - It caches the result in the
cache.discoverybin.
Then createInstance($plugin_id, $configuration) instantiates the matching class.
That caching explains reflex number one when a plugin doesn’t show up: drush cr. Until the discovery cache is cleared, Drupal doesn’t see your new class.
PHP attributes or annotations?
Up to Drupal 10.1, definitions were written as Doctrine annotations (@Block(...) comments). Since Drupal 10.2, core uses PHP 8 attributes:
// Old syntax (annotation)
/**
* @Block(
* id = "my_block",
* admin_label = @Translation("My block"),
* )
*/
// Current syntax (attribute)
#[Block(
id: 'my_block',
admin_label: new TranslatableMarkup('My block'),
)]
Annotations still work for plugin types that provide an attribute, but they trigger a deprecation and will be removed in Drupal 13. All new code should use attributes, and existing code can migrate today.
Step 1: create a plugin of an existing type
Let’s start with the most common case: a block listing the latest published articles, with a configurable number of items.
File src/Plugin/Block/LatestArticlesBlock.php in the my_module module:
<?php
declare(strict_types=1);
namespace Drupal\my_module\Plugin\Block;
use Drupal\Core\Block\Attribute\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
#[Block(
id: 'my_module_latest_articles',
admin_label: new TranslatableMarkup('Latest articles'),
category: new TranslatableMarkup('My module'),
)]
final class LatestArticlesBlock extends BlockBase implements ContainerFactoryPluginInterface {
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
private readonly EntityTypeManagerInterface $entityTypeManager,
) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
}
public function defaultConfiguration(): array {
return ['count' => 5];
}
public function blockForm($form, FormStateInterface $form_state): array {
$form['count'] = [
'#type' => 'number',
'#title' => $this->t('Number of articles'),
'#min' => 1,
'#max' => 20,
'#default_value' => $this->configuration['count'],
];
return $form;
}
public function blockSubmit($form, FormStateInterface $form_state): void {
$this->configuration['count'] = (int) $form_state->getValue('count');
}
public function build(): array {
$storage = $this->entityTypeManager->getStorage('node');
$ids = $storage->getQuery()
->accessCheck(TRUE)
->condition('type', 'article')
->condition('status', 1)
->sort('created', 'DESC')
->range(0, $this->configuration['count'])
->execute();
$items = [];
foreach ($storage->loadMultiple($ids) as $node) {
$items[] = $node->toLink()->toRenderable();
}
return [
'#theme' => 'item_list',
'#items' => $items,
// The block must be invalidated whenever a node is created, updated or deleted.
'#cache' => ['tags' => ['node_list']],
];
}
}
What to remember:
- The location is mandatory:
src/Plugin/Block, namespaceDrupal\my_module\Plugin\Block. Get the folder wrong and the plugin is invisible, with no error at all. - The attribute lives in
Drupal\Core\Block\Attribute\Block. Watch your IDE’s auto-import, which sometimes suggests the old annotation classDrupal\Core\Block\Annotation\Block. $this->configurationholds the configuration of this instance.defaultConfiguration()provides the defaults,blockForm()andblockSubmit()handle the form.- Cache metadata is your job: without the
node_listtag, the block would show the same list until the next cache clear. See the article on the Cache API.
Dependency injection, with or without create()
The plugin implements ContainerFactoryPluginInterface: that’s the signal telling the manager “pass me the service container”. Historically, you had to write a create() method to fetch each service:
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): static {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager'),
);
}
With Drupal 11.3, you no longer need it: Drupal\Core\Plugin\PluginBase provides a create() method that autowires the constructor arguments from their type (EntityTypeManagerInterface is an alias of the entity_type.manager service). That’s why the example above can do without it. If your module must stay compatible with earlier versions, keep the explicit create() method.
When the type alone doesn’t identify the service (several services implement the same interface), Symfony’s #[Autowire] attribute names the one you want:
use Symfony\Component\DependencyInjection\Attribute\Autowire;
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
#[Autowire(service: 'cache.data')]
private readonly CacheBackendInterface $cache,
) {
The configuration schema
A placed block’s configuration is exported by drush cex. Declare its schema in config/schema/my_module.schema.yml, or config validation and your tests will remind you:
block.settings.my_module_latest_articles:
type: block_settings
label: 'Latest articles'
mapping:
count:
type: integer
label: 'Number of articles'
Step 2: create your own plugin type
This is where the Plugin API really shines. Back to the notification module: we want any module to be able to add a notification channel.
You need five pieces:
notifier/
├── notifier.services.yml # the plugin manager service
└── src/
├── Attribute/Notifier.php # the attribute describing a plugin
├── NotifierInterface.php # the contract
├── NotifierPluginBase.php # a convenient base class
├── NotifierPluginManager.php # the manager
└── Plugin/Notifier/EmailNotifier.php # a first plugin
1. The attribute: what describes a plugin
<?php
declare(strict_types=1);
namespace Drupal\notifier\Attribute;
use Drupal\Component\Plugin\Attribute\Plugin;
use Drupal\Core\StringTranslation\TranslatableMarkup;
/**
* Defines a Notifier plugin.
*/
#[\Attribute(\Attribute::TARGET_CLASS)]
final class Notifier extends Plugin {
public function __construct(
public readonly string $id,
public readonly TranslatableMarkup $label,
public readonly ?TranslatableMarkup $description = NULL,
public readonly ?string $deriver = NULL,
) {}
}
Each public property becomes a key of the definition: $definition['label'], $definition['description']. The deriver property is optional, but providing it now costs nothing.
2. The contract
<?php
declare(strict_types=1);
namespace Drupal\notifier;
use Drupal\Component\Plugin\PluginInspectionInterface;
interface NotifierInterface extends PluginInspectionInterface {
/**
* The human-readable name of the channel.
*/
public function label(): string;
/**
* Sends a notification. Returns TRUE on success.
*/
public function send(string $subject, string $message): bool;
}
PluginInspectionInterface adds getPluginId() and getPluginDefinition(), which every plugin should expose.
3. The base class
<?php
declare(strict_types=1);
namespace Drupal\notifier;
use Drupal\Core\Plugin\PluginBase;
abstract class NotifierPluginBase extends PluginBase implements NotifierInterface {
public function label(): string {
return (string) $this->pluginDefinition['label'];
}
}
It holds what all channels share. Other modules will extend this class instead of implementing the interface from scratch.
4. The plugin manager
<?php
declare(strict_types=1);
namespace Drupal\notifier;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\notifier\Attribute\Notifier;
final class NotifierPluginManager extends DefaultPluginManager {
public function __construct(
\Traversable $namespaces,
CacheBackendInterface $cache_backend,
ModuleHandlerInterface $module_handler,
) {
parent::__construct(
'Plugin/Notifier', // Subfolder scanned in every module.
$namespaces,
$module_handler,
NotifierInterface::class, // Interface every plugin must implement.
Notifier::class, // Attribute carrying the definition.
);
// Lets other modules implement hook_notifier_info_alter().
$this->alterInfo('notifier_info');
// Caches the definitions in cache.discovery.
$this->setCacheBackend($cache_backend, 'notifier_plugins');
}
}
DefaultPluginManager does all the work: attribute discovery, derivers, the alter hook, caching and instantiation (including calling create()).
5. The service
# notifier.services.yml
services:
plugin.manager.notifier:
class: Drupal\notifier\NotifierPluginManager
parent: default_plugin_manager
The default_plugin_manager parent service provides the three constructor arguments: the modules’ namespaces, the cache.discovery cache and the module handler.
A first plugin
<?php
declare(strict_types=1);
namespace Drupal\notifier\Plugin\Notifier;
use Drupal\Core\Mail\MailManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\notifier\Attribute\Notifier;
use Drupal\notifier\NotifierPluginBase;
#[Notifier(
id: 'email',
label: new TranslatableMarkup('Email'),
description: new TranslatableMarkup('Sends the notification by email.'),
)]
final class EmailNotifier extends NotifierPluginBase implements ContainerFactoryPluginInterface {
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
private readonly MailManagerInterface $mailManager,
) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
}
public function send(string $subject, string $message): bool {
// The message itself is built in hook_mail(), not shown here.
$result = $this->mailManager->mail(
'notifier',
'notification',
$this->configuration['to'],
'en',
['subject' => $subject, 'message' => $message],
);
return (bool) $result['result'];
}
}
Using the plugin type
/** @var \Drupal\notifier\NotifierPluginManager $manager */
$manager = \Drupal::service('plugin.manager.notifier');
// List the available channels, without instantiating a single class.
$options = [];
foreach ($manager->getDefinitions() as $id => $definition) {
$options[$id] = $definition['label'];
}
// Instantiate a channel with its configuration, then use it.
$notifier = $manager->createInstance('email', ['to' => 'ops@example.com']);
$notifier->send('Import finished', '1,234 products imported.');
In a class (controller, service, form), inject plugin.manager.notifier instead of calling \Drupal::service().
From now on, a third-party module only has to drop a class into its own src/Plugin/Notifier folder with the #[Notifier] attribute: after a drush cr, its channel shows up in $options, without a single line changed in your module.
Step 3: derivers, one plugin that produces many
New requirement: one Slack channel per configured Slack room. The rooms are defined in the site configuration (#alerts, #releases…) and the administrator must see one channel per room in the list.
Writing one class per room makes no sense: the list changes without a deployment. That’s the job of a deriver: a class that takes a base definition and produces as many definitions as needed.
#[Notifier(
id: 'slack',
label: new TranslatableMarkup('Slack'),
deriver: SlackChannelDeriver::class,
)]
final class SlackNotifier extends NotifierPluginBase implements ContainerFactoryPluginInterface {
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
private readonly ClientInterface $httpClient,
private readonly ConfigFactoryInterface $configFactory,
) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
}
public function send(string $subject, string $message): bool {
// getDerivativeId() returns the part after the colon: "alerts" for "slack:alerts".
$channel = $this->getDerivativeId();
$webhook = $this->configFactory->get('notifier.settings')->get("slack_channels.$channel.webhook");
$response = $this->httpClient->request('POST', $webhook, [
'json' => ['text' => "*$subject*\n$message"],
]);
return $response->getStatusCode() === 200;
}
}
The deriver, in src/Plugin/Derivative/SlackChannelDeriver.php:
<?php
declare(strict_types=1);
namespace Drupal\notifier\Plugin\Derivative;
use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Symfony\Component\DependencyInjection\ContainerInterface;
final class SlackChannelDeriver extends DeriverBase implements ContainerDeriverInterface {
public function __construct(
private readonly ConfigFactoryInterface $configFactory,
) {}
public static function create(ContainerInterface $container, $base_plugin_id): static {
return new static($container->get('config.factory'));
}
public function getDerivativeDefinitions($base_plugin_definition): array {
$channels = $this->configFactory->get('notifier.settings')->get('slack_channels') ?? [];
foreach ($channels as $key => $channel) {
$this->derivatives[$key] = [
'label' => new TranslatableMarkup('Slack: @name', ['@name' => $channel['name']]),
] + $base_plugin_definition;
}
return $this->derivatives;
}
}
With two rooms configured, getDefinitions() now returns email, slack:alerts and slack:releases. A derived plugin’s ID always has the form base:derivative, and the plugin knows both parts through getBaseId() and getDerivativeId().
Derivers are everywhere in core: one menu block per menu (system_menu_block:main), one block per view display (views_block:…), one local task per entity type…
Two important rules:
- Derived definitions are cached. When the list of rooms changes, clear the definitions cache, for example in the settings form’s
submitForm():$this->notifierManager->clearCachedDefinitions();. - Never put a secret in a definition. Definitions are stored in
cache.discoveryand exposed to every module through the alter hook. That’s why the webhook URL is read from configuration at send time, not stored in the definition.
Letting other modules alter definitions
Thanks to alterInfo('notifier_info'), any module can change the definitions before they are cached. With Drupal 11’s object-oriented hooks:
<?php
declare(strict_types=1);
namespace Drupal\my_module\Hook;
use Drupal\Core\Hook\Attribute\Hook;
use Drupal\my_module\Notifier\AuditedEmailNotifier;
final class NotifierHooks {
#[Hook('notifier_info_alter')]
public function notifierInfoAlter(array &$definitions): void {
// Swap the email channel's class for one that logs every message sent.
$definitions['email']['class'] = AuditedEmailNotifier::class;
}
}
That’s the clean way to replace the implementation of a plugin provided by another module, without a patch.
Plugin, service, tagged service or event?
The Plugin API isn’t the answer to everything. Here’s how to choose.
| Need | Tool | Example |
|---|---|---|
| A single implementation, replaceable globally | Service (possibly decorated) | The URL generator |
| Several implementations, all called, in priority order | Tagged services (collectors) | Path processors, breadcrumb builders |
| Reacting to something that happens | Event (Event API) or hook | An HTTP response going out, an entity being saved |
| Several implementations to choose from, with a label for the UI and per-instance configuration | Plugin | Blocks, field formatters, notification channels |
The most reliable signal: if the administrator or the calling code picks one implementation among several and gives it settings, it’s a plugin.
Debugging
List the plugins a manager knows about:
drush php:eval 'print_r(array_keys(\Drupal::service("plugin.manager.notifier")->getDefinitions()));'
Inspect one definition, for example to check which class is used after an alter hook:
drush php:eval 'print_r(\Drupal::service("plugin.manager.block")->getDefinition("system_branding_block"));'
And, always, after adding or moving a plugin class:
drush cr
Common pitfalls
1. The plugin doesn’t show up. In order: cache not cleared, folder or namespace mismatch (src/Plugin/Notifier ↔ Drupal\my_module\Plugin\Notifier), attribute imported from the wrong namespace, module not enabled. None of these produce an error: the plugin is silently ignored.
2. Two plugins with the same ID. The last one discovered wins, with no warning. Prefix your IDs with the module name (my_module_latest_articles).
3. Objects in the configuration. An instance’s configuration is often exported to YAML (blocks, formatters). It must only hold scalars and arrays, and be described by a schema.
4. An expensive deriver. The deriver runs every time the discovery cache is rebuilt. Loading thousands of entities to build definitions slows down every drush cr and every first request after a cache clear.
5. Forgetting cache metadata in rendering plugins. A block that shows data without cache tags or contexts will show stale data, or worse, another user’s data. See the article on access control and cacheability.
6. Still writing annotations. They still work, but they are deprecated and will be gone in Drupal 13. You might as well write code that won’t need migrating.
Checklist
- The need justifies a plugin: several implementations to choose from, with metadata and per-instance configuration.
- The attribute describes everything the admin UI needs, without instantiating the class.
- The interface extends
PluginInspectionInterface, and a base class holds the shared code. - The manager extends
DefaultPluginManagerand callsalterInfo()andsetCacheBackend(). - The service inherits from
default_plugin_manager. - Plugins get their dependencies through injection, never through
\Drupal::service(). - Instance configuration has a schema.
- Derivers stay light, and the definitions cache is cleared when their source changes.
- No sensitive data in definitions.
The Plugin API asks for a bit of structure up front: an attribute, an interface, a manager, a service. In return, your module becomes extensible by any other module, exactly like Drupal core.
