The Drupal 8 plugin system - part 2

We saw in part 1 how plugins help us in writing reusable functionality in Drupal 8. There are a lot of concepts which plugins share in common with services, like:

  1. limited scope. Do one thing and do it right.
  2. PHP classes which are swappable.

Which begs the question, how exactly are plugins different from services? If your interface expects implementations to yield the same behaviour, then go for services. Otherwise, you should write it as a plugin.

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.

Annotations in Drupal 8

Annotations are PHP comments which hold metadata about your function or class. They do not directly affect program semantics as they are comment blocks. They are read and parsed at runtime by an annotation engine.

Annotations are already used in other PHP projects for various purposes. Symfony2 uses annotations for specifying routing rules. Doctrine uses them for adding ORM related metadata.Though handy in various situations, their utility is debated about a lot, like:

  1. How to actually differentiate between annotations and actual user comments?

2.

Drupal 8 asset management using libraries.yml

One of the things you are likely to do if you write a custom module or a theme is include third party Javascript and/or CSS assets in it. Previously, this used to be a clumsy hook_library_info() array but is replaced by a YML file in D8. It makes asset management look more organized and easier to edit. Let's see how to do this for the colorbox module.

The new YML file will have the naming convention modulename.libraries.yml.

Pages