Journey To Drupal 8 Plugin’s

Drupal 8 has a powerful feature called Plugin that helps creating multiple elements, such as blocks, field types, field formatters, and many more.

Plugins can be created as part of modules in Drupal 8 and they provide a swappable and specific functionality that provides pluggable and stand-alone components which can be re-used whenever required. This is pretty much similar to the earlier versions of Drupal where modules and blocks were used as reusable components and programmable entities.

In Drupal 8,  Plugin manager is responsible for managing the plugins and both the definition and instantiating the instances of plugins.

The plugin system provides means to create specialized objects in Drupal that do not require the robust features of the entity system.

A Plugin is a combination of following elements:

  • Plugin Manager
  • Interface
  • Annotation Class


Plugin Manager

Plugin managers are defined as a service and used for discovery of a plugin.


Initially, we need to implement an Interface by adding a custom class in defining all required methods to make it work.

Annotation Class

Annotations are used to give a definition to a Plugin. This is a combination of different parameters in a comment style, however, that is readable by plugin manager.

The example given below follows the creation of new plugin type called Calculator that calculates  Area Of Shapes (Rectangle, Triangle, and Square) and BMI.

The primary step is to create a service that acts as a plugin manager and for that create a new file in module’s src directory called CalculatorPluginManager.php.

We need to override the \Drupal\Core\Plugin|DefaultPluginManager class constructor to define the module handler and cache backend.

We override the constructor so that we can specify a cache key. This allows
plugin definitions to be cached and cleared properly, otherwise our plugin manager
will continuously read the disk to find plugins.

The next step is to create a in module’s directory. This will initiate the plugin discovery to Drupal.

Next step is to define plugin interface and that will be used by the plugin to implement the essential methods for the working of the plugin. Create a CalculatorInterface.php file in module’s src directory to hold the interface.

Create CalculatorBase.php in your module’s src directory. This class will implement our CalculatorInterface interface:

Now add a controller to make the plugin visible on a page.

The plugin has been created under the src directory of the module.

Annotation directory is also under src directory and one more file called Calculator.php, see the example below.


By using the understanding of a plugin’s architecture in Drupal 8, multiple types of plugins can be created to resolve a different kind of problems.

Reference of the code for the plugin created above can be taken from the GitHub. Please see the link below.

About The Author