Module Development in Drupal 8

AJ Roach Profile Photo
A. J. Roach

on

August 31, 2013

Module Development in Drupal 8

I spent a couple of hours today doing something that I've been wanting to do for a while now, but just hadn't made the time -- going through the changelog for drupal 8, and seeing if I could port a few custom modules from D7 to D8. I thought I'd share what I've learned thus far. As an example, let's take a look at this simple D7 module (that really does nothing other than serve as a nice example for this blog post) called 'test'.

test.info
; $Id:$
name = Test
description = "Test Module"
package = "Test"
core = 7.x
files[] = test.module


test.module
<?php
/**
* @file
* Test module
*
*/
/*
* Implementation of hook_menu
*/
function test_menu() {
 
$items = array();
 
$items['test/%'] = array(
   
'title' => t('Test'),
   
'description' => t('Test'),
   
'page callback' => '_test',
   
'page arguments' => array(1),
   
'access callback' => TRUE,
   
'type' => MENU_CALLBACK
 
);
  return
$items;
}
function
_test($variable) {
 
$output = $variable;
  return
$output;
}
function
test_block_info() {
 
$block = array();
 
$block['test']['info'] = t('Test Block');
  return
$block;
}
function
test_block_view($delta = '') {
 
$block = array();
  switch (
$delta) {
    case
'test':
     
$block['subject'] = t('Test block');
     
$block['content'] = t('Here is the content');
  }
  return
$block;
}
?>

As you can see, the module registers a menu callback at the path 'test/%'. The callback simply prints the argument passed in via the url. The other thing the test module does is implement a custom block with hook_block_info and hook_block_view. Let's look at how to port the test module to D8.

I guess it's worth noting first of all, that you can install D8 via git like so:

git clone --branch 8.x http://git.drupal.org/project/drupal.git
Take a look at https://drupal.org/node/3060/git-instructions/8.x for a more in-depth discussion on how to install D8.

Once your installation is finished and you're up and running, you can get down to some coding. The first thing to note is that your .info file is now going to be a yaml file. So you'll need to rename the test.info file to test.info.yml. You can get the specifics of yaml by clicking through the preceding link, but the jist of it isn't all that different from how .info files were set up in Drupal 7. Replace all '=' signs with ':'. If an array was called for in D7 (for example with dependencies[] = node, etc), you'll now use indention and a '-' like so:

dependencies
  - node
  - some_other_custom_module
You can get more information about yaml and how it specifically relates to Drupal 8 .info files by visiting https://drupal.org/node/2000204. Here's what the test.info.yml file should look like:

name: Test
description: Test module
core: 8.x
package: Test
type: module

Next let's move on to the test.module file:

<?php

/**
* @file
* Test
*
*/

/**
* Implementation of hook_menu()
*/
function test_menu() {
 
$items = array();
 
 
$items['test/{variable}'] = array(
   
'title' => 'Test',
   
'route_name' => 'test_page',
   
'type' => MENU_DEFAULT_LOCAL_TASK,
  );
 
  return
$items;
}
?>

One of the first things you'll notice if you're paying attention is that there are no block hooks in the .module file anymore. That's because blocks in Drupal 8 are plugins. We'll get to that in a few moments. The other thing you'll notice is that the hook_menu implementation doesn't have any callback information. In Drupal 8, as part of the WSCCI, those old procedural callbacks have been swapped out for an OO Symfony2 routing system. hook_menu is still there, but now it's ONLY used to define menu items, NOT to define their paths, or routes as it were. You can see that there's a new key in the array called 'routing_name'. Remember this as it'll be important in a few minutes. You can also see that the old argument placeholder, %, is now replaced by a bracket syntax: {variable_name}. This variable_name will be automatically passed as $variable_name to the callback method that we will define in our route controller class. What's a route controller class you say? Well, the way it works now is that we'll create another yaml file (called modulename.routing.yml) to map any incoming request path to a method contained within a controller class for this module.

The route controller class is stored in the file system according to the much maligned PSR-0 standard for autoloading code only when it's needed. I won't get into this too much, but it basically consists of the idea that your file system should be structured in a standard way. For Drupal 8's routing controller, this means having a directory structure starting at your modulename root directory that looks like lib/Drupal/modulename/Controller/ControllerName.php. If you think having to adhere to such a long and redundant file structure is ridiculous, you're not alone. The plan as of now is to move to the slightly less-ridiculous forthcoming proposed PSR-4 for class loading, but I digress...

Let's take a look at the test.routing.yml file:

test_page:
  pattern: '/test/{variable}'
  defaults:
    _content: 'Drupal\test\Controller\TestController::testPage'
  requirements:
    _permission: 'access content'
Remember the routing_name => 'test_page' in the $items[] array from test.module? You can see that it is used here as the unique name for this route. We then define the pattern to match for the incoming request, and as you can see it contains the {variable} placeholder. Next, in the _content variable of the defaults section we reference the Controller class and method that will be called when this route is matched. Referencing this method in '_content' means that Drupal will wrap whatever is returned from this method with the rest of the page layout. Lastly, we set the required permission needed to access this page.

Next we need to create the route controller class that we referenced in the test.routing.yml file. So, make sure you have the directory structure as I described above (to adhere to the PSR-0 “standard”). Starting at test (your module directory) the filesystem should be structured like 'test/lib/Drupal/test/Controller'. Inside that last 'Controller' directory, you'll create your TestController.php file like this:

<?php

namespace Drupal\test\Controller;

class TestController {
 
  public function testPage($variable) {
    $build = array(
      '#type' => 'markup',
      '#markup' => t($variable),
    );
   
    return $build;
  }
}
As you can see, this is a pretty standard php class file. I've defined the testPage method (as it was referenced in the test.routing.yml file), and it returns a build array. The interesting thing to note here is that as I described earlier, the $variable that is passed into the testPage method is the argument that comes in on the url when the route is fired. So if you now go to your drupal 8 site and navigate to admin/config/development/performance, then clear all caches, then navigate to admin/modules and enable the test.module, you should then be able to navigate to http://yoursite/test/it-works, and see a page that just prints out $variable (“it-works”). Please note that this is an extremely simplified example. I'm not taking dependency injection into account at all. That would require a bit more code. We'd need the TestController class to implement the ControllerInterface interface. For now, I'll leave that to you, but I might revisit dependency injection in a future blog post.

Now that we've sorted the routing, let's look at how to create a custom block in our test module. In Drupal 8, blocks are plugins, so to create a custom block we'll need to create a Plugin and a Block directory in our file structure. Change into the test/lib/Drupal/test directory and do

mkdir -p ./Plugin/Block
Now you should have a directory structure like 'test/lib/Drupal/test/Plugin/Block'. In that Block directory, we'll create our TestBlock.php file. The file looks like this:
<?php

/**
* @file
* Contains \Drupal\test\Plugin\Block\TestBlock
*/

namespace Drupal\test\Plugin\Block;

use Drupal\block\BlockBase;
use Drupal\block\Annotation\Block;
use Drupal\Core\Annotation\Translation;

/**
* Provides a test block.
*
* @Block(
*  id = "test_block",
*  admin_label = @Translation("Test Block")
* )
*/
class TestBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    $this->configuration['label'] = t('Test block');
    return array(
      '#children' => t('Here is the content'),
    );
  }
}
Again, this is a pretty standard php class. TestBlock extends the BlockBase class. BlockBase has a number of methods that can be overridden here to do all sorts of cool things with your custom blocks. I'm not going to go into those right now though. We'll just stick with the build method which lets you put content into your block. The most important thing to notice here is the @Block directive in the comments before the TestBlock class definition. This is Doctrine-style annotation. This is how Drupal 8 discovers and gets metadata about your plugins. This is all new for D8, and without going into it in too much detail, the old way of getting metadata was very memory-intensive so this new way was adopted and implemented. You can find out all about it by clicking here. Also note that the use lines are required.

Once you save this file, navigate to admin/structure/block, and you should see your custom block in the list on the right-hand side of the page. Click it to “place” the block, then find the block in the list in the main part of the block page and add it to the region that you want.

Well that does it for this post. Keep in mind that this is all new to me as well, and I'm just figuring it out as I go -- mostly by reading through the changelog. If you see anything here that could be done in a more efficient way, or if I've missed anything, please don't hesitate to make suggestions in the comments.

Share it!

I am waiting to see what Drupal 8 has to offer, as far as I had used Drupal 7 the CMS is good, but not good enough. The earlier Drupal version was great, moreover being a Drupal website developer was fun too, then. Many modules used earlier were not supported by Drupal 7 too.
In Drupal * the main things is .info.yml file.