Using PHP attributes for Drupal plugins

Starting with Drupal version 10.2, it will be possible to use PHP attributes instead of annotations for some plugins. Currently, this applies to Action and Block plugins. For more information, please see the following change record:

https://www.drupal.org/node/3395575

Let's take one of my modules, Facets Block, as an example. Here's how the block plugin would look with annotations and with attributes.

Before:

/**
 * Provides a 'Facets Block' block.
 *
 * @Block(
 *  id = "facets_block",
 *  admin_label = @Translation("Facets Block"),
 * )
 */
class FacetsBlock extends BlockBase implements ContainerFactoryPluginInterface {
  ...
  ...
}

After (Drupal 10.2+):

use Drupal\Core\Block\Attribute\Block;
use Drupal\Core\StringTranslation\TranslatableMarkup;

/**
 * Provides a 'Facets Block' block.
 */
#[Block(
  id: 'facets_block',
  admin_label: new TranslatableMarkup('Facets Block')
)]
class FacetsBlock extends BlockBase implements ContainerFactoryPluginInterface {
  ...
  ...
}

To make this work, don't forget to add the appropriate classes (Block and TranslatableMarkup) in the use section and to clear the cache.

Using PHP attributes, rather than annotations that are essentially PHP comments, for adding structured metadata to classes is more appealing to me. So, I definitely plan to use this in the future.

About the Author

Goran Nikolovski is a web and AI developer with over 10 years of expertise in PHP, Drupal, Python, JavaScript, React, and React Native. He founded this website and enjoys sharing his knowledge.