D8: Creating a simple block module

With the first Beta of Drupal 8 released this week on DrupalCon Amsterdam it is time to get learning Drupal 8 and all the changes that are in it. With the adoption of object oriented programming and the Symfony components Drupal 8 is leaping from the procedural PHP 4 style to the full fledged PHP 5.3+ style object oriented model.
Personally I think this is a great improvement and I’m very happy with it. PHP is getting a really nice language with a good object model.

Creating the files

Creating a module is fairly easy and requires some directories and a yaml file. In the directory modules create a new directory custom and in there the directory hello.

The hello.info.yml will look like this. The content is almost the same as a <D8 info file.

name: Hello
type: module
description: 'Simple testmodule'
package: Leon

version: 0.1
core: 8.x

The complete directory structure will look like this. It looks a little overkill for such a simple block but it gives a good structure and skeleton for additions to the module in a structured and consistent way. Over time a module will always grow so starting a module with a structure that can expand is a good thing. With this directory structure in place and the namespace Plugin/Block Drupal will discover your block automatically. Thank to the PSR-4 standard.

- modules/custom
  - hello
    - src
      - Plugin
        - Block
          - HelloBlock.php
    - hello.info.yml

The HelloBlock.php file will contain the following. I will not explain everything in detail because I think it should be clear what everything means. The most important parts are:

  • Annotations, The use of annotations is important and replaces the block_info hook. The id and label for this block are given in the annotation, the admin interface will use this to discover which blocks are available.
  • Build(), The build method will be called when the block is to be build and expects and build array in return. This is the most important method for a block and comparable to hook_block_view()
  • BlockBase, Because of the OO model this class should extend BlockBase, this gives a lot of functionality out of the box and is an essential starting point for the block.

This is everything you need for a simple block plugin.