The Drupal 8 plugin system - part 1

Plugins are swappable pieces of code in Drupal 8. To see how different they are from hooks, let's take an example where we want to create a new field type.

In Drupal 7, this involves:

  1. Providing information about the field

    hook_field_info - describes the field, adds metadata like label, default formatter and widget.

    hook_field_schema - resides in the module's .install file. Specifies how the field data is stored in the database.

    hook_field_validate - validates the field content before it is persisted in the database.

    hook_field_is_empty - criteria which decides when this field is considered "empty".

  2. Describe how the field will be displayed using,

    hook_field_formatter_info - metadata about different types of formatters.

    hook_field_formatter_view - implementation of the formatters defined above, mostly spits out HTML.

  3. Define a widget for the field type.

    hook_field_widget_info - provides information about widgets. For instance, a calendar would be a widget for a date field.

    hook_field_widget_form - implements the widgets.

In Drupal 8, all the 3 steps mentioned above(field info, formatters and widgets) are 3 types of plugins.

  1. Providing information about the field. This is done by the FieldType plugin which extends FieldItemBase. The FieldItemBase class has schema, metadata and validation encapsulated which will need to be overriden by the developer.

  2. Field formatter. Implemented by extending FormatterBase. the viewElements() function needs to be overridden to provide a renderable array for a field value. This is similar to the hook_field_formatter_view in Drupal 7.

  3. Widgets are implemented by subclassing WidgetBase.

There is many more to creating field types than that, but that's all you need to know from a plugins perspective.

What did we gain by changing fields from being a hook based system to plugins based? For one, the code became more encapsulated. The definition and implementation is wrapped in one place. Another benefit we reaped by following OO principles is inheritance. Plugins are designed to be extensible. This allows us to subclass similar functionality and achieve one of the most coveted ideals of software engineering, i.e. code reuse. Example of plugin inheritance in Drupal 8 core

In the next part, we will look at the concept of plugin discovery and some common plugin types exposed by Drupal 8 core.