An annotation is metadata that can be added to a file, class, function, or variable. These can be used to add information describing plugins without having to write a separate function. In Drupal 7, in order to expose a block, you needed to implement at least two hooks: hook_block_info to describe the block, give it a label, a machine name, describe caching, and so on; and then at least hook_block_view to render it. The same file that contains the plugin implementation also contains the metadata about it. It's encoded as a PHP docblock on the class itself. You can see that above the class declaration in our TestBlock.php file.
/**
* Provides a 'TestBlock' block.
*
* @Block(
* id = "test_block",
* admin_label = @Translation("Test block"),
* )
*/
As of PHP 5.1, the PHP Reflection API has allowed runtime inspection of multi-line doc comments (also called T_DOC_COMMENTS) using the ReflectionClass::getDocComments method. One important note is that only doc comments, that is, ones that begin with /** , are retrieved. Any comments that are normal multi-line comments (T_COMMENT) that begin with a single asterisk like /* are not stored in the opcode cache.
Symfony uses annotations to provide essential metadata to various handlers, though at the moment, Drupal only uses them for plugins. For instance, the @Block declaration invokes and attaches the \Drupal\Core\Block\Annotation\Block class, which defines the elements that can be used in the annotation:
- admin_label: The label that is shown in the administrative UI
- Category: The group that the plugin appears under in the administrative UI
- Derivative: It allows a plugin to be shown as and act like multiple plugins when the functionality is the same, for example, menu blocks
From a plugin object you can call PluginInspectionInterface::getPluginDefinition to retrieve the array that contains the annotation data. Looking at our new block plugin, it extends BlockBase, which implements BlockPluginInterface, which extends PluginInspectionInterface. So, to get the machine name of a block entity, you would do the following:
$machine_name = $block->getPlugin()->getPluginDefinition()['id'];