Drupal 8 Annotations

Similar to symfony Drupal8 annotations are written in php as a comment above a class or a function and contain metadata about a class or a function.

Annotations used by Drupal8’s Plugin

Annotations are only used by the Plugin system in Drupal 8. To help understand better annotation in drupal 8 you have info.ymal file that tells the information about the module, route ymal files tells drupal about different routes, in menu yaml file you tell/inform drupal which links to add to menu system. Annotations are similar concept for plugins. Some of the plugins types provided by the core are:

1) Blocks (see /src/Plugin/Block/ for many examples)

2) Field formatters, Field widgets (see /src/Plugin/Field/ for many examples)

3) All Views plugins (see /src/Plugin/views/ for many examples)

4) Conditions (used for Block visibility in the core)

5) Migrate source, process & destination plugins

PSR-4

Plugins using annotations are registered in PHP files using the PSR-4 standard, which is followed by Drupal core.

To register your plugin, put a file in a folder relative to your Drupal module root: src/Plugin/$plugin_type/Example.php.

Example: core/modules/ckeditor/src/Plugin/CKEditorPlugin/Internal.php

s In order to tell the system that something is a plugin you have to place the following comment right before your class definition (with @Plugin replaced with the particular plugin type):

/**
 * @Plugin(
 *
 * )
 */
Annotation Example

An example for a block.

/**
 * Provides a 'Welcome' Block
 *
 * @Block(
 *   id = "welcome_block",
 *   admin_label = "Welcome block",
 * )
 */

Block manager scans files looking for @Block annotation tag to find block instances.

The @Block annotation ensures that the block manager discovers this custom block and makes it available to be added to a region. The id of welcome_block is the machine name and the admin_label (Hello block) will appear in the block interface’s list of blocks.