Plugins

Plugins extend or alter existing parts of a system. In Drupal, plugins are used for defining blocks, field types, migration processors, and many other things.

Plugins have a defined structure and provide necessary dependencies, making it easy for a developer to focus on the logic. You can copy an existing plugin file and modify it for your own needs.

There are also ways to generate plugins with Drush.

 

Let's take a look at a basic block plugin - powered by Drupal.

Plugin Namespaces

Namespaces are necessary to allow classes to have the same name in a codebase without using the wrong one in code. They provide a full path to reference the class. This is related to the actual directory, but it is not the same, and it is important to note the differences.

The "Powered by Drupal" block has this namespace:

namespace Drupal\system\Plugin\Block;

It is located in:

web/core/modules/system/src/Plugin/Block/SystemPoweredByBlock.php

 

"namespace Drupal" will always be the start for Drupal classes.

\system is the name of the module, in this case it's the core system module.

\Plugin\Block is the directory path within the module's /src directory.

 

When in doubt, use the same file path and namespace as another plugin of the same type, and just change the module name in the namespace.

 

Plugin Annotations

Annotations are comments that define configuration for a class.

/**
 * Provides a 'Powered by Drupal' block.
 *
 * @Block(
 *   id = "system_powered_by_block",
 *   admin_label = @Translation("Powered by Drupal")
 * )
 */
class SystemPoweredByBlock extends BlockBase {}

In this case, we define the id and admin_label. These are used to reference the plugin and label it in the interface.

Plugin Classes

Plugins extend a base class so they inherit an interface, default functions, and dependencies.

Some functions will be required to implement, and some you can optionally override or extend.

Generate Plugins

Drush can generate plugin code for you to customize. This is a handy shortcut to get into the code without thinking about the plumbing.

Questions