Drupal 8 Module Development, Part 3: Plugins

lego

Drupal 8 Module Development, Part 3: Plugins

As with any new version of Drupal, a number of contributed modules will be refactored, and pulled into core. Among them is ctools which has been a Drupal staple since version 6. If you're at all familiar with the current ctools implementation of plugins, the Drupal 8 version of this is very similar and will be used to replace a number of hooks. This is another important step in moving towards less procedural and more object-oriented code.

Plugins are a pretty broad subject which I'm sure will get covered more, both here and on other blogs as time progresses. In this example, we'll focus on how and why they're replacing hooks, as well as how to use them for simple tasks like creating blocks.

What are they?

Plugins are not too dissimilar from hooks. They are used to modularly include elements and functionality into a module via its dependent modules. This is pretty much exactly what hooks are for, except they are packaged differently and the implementation is much cleaner.

Creating Blocks

Step 1: Create your plugin file

Start by creating the file foobar/lib/Drupal/foobar/Plugin/Block/FoobarBlock.php with an empty class. This is where we will define the properties of our block which would have previously been handled with hook_block_info, hook_block_view, hook_block_configure, and hook_block_save.

Step 2: Block Methods

There are a number of methods that can be used to override the defaults defined in BlockBase class to provide custom functionality.

access

Used to specify who can view the block.

blockBuild

Used to define the renderable output of the block.

blockForm, blockValidate, and blockSubmit

Used to add additional fields to the block configuration form and manage the validation and submit behavior of the form.

For this example, we'll use the blockBuild method.

Step 3: Annotation

Annotation is something that has been introduced by Symfony and is used to register a plugin with Drupal much like the .info file for modules. Annotation is basically comments designed to specify parameters about the code that it is surrounding. Without the annotation, Drupal will not recognize your plugin, and it will not work.

Fork this project on GitHub

Any questions or comments? Let us know.

Related Posts

Drupal 8 Module Development, Part 2: Forms

Ian Whitcomb
Read more

Drupal 8 Module Development, Part 1: Getting Started

Ian Whitcomb
Read more

Optimize Social Connections Through Module Development and APIs

Brent Bice
Read more

Managing your DrupalVM Environment: Vagrant Plugins and SED Scripts

Kyle Taylor
Read more

Think Before You Add A Module

Felipa Villegas
Read more

Drupal Content Optimizer Module Makes SEO a Breeze

Chris Sloan
Read more