Skip to main content

Build a Simple Module with Drupal Console

Dec 18 '15
drupal console illo


I recently stumbled upon this thing call Drupal Console — and I must say that I’m impressed. Although I have not completely integrated it into my workflow, Drupal Console has a lot of features that will help make Drupal 8 development virtually painless. It also comes with useful documentation so you can hit the ground running.

So, first things first, what is it? Drupal Console is a command line tool that can interact with a Drupal 8 installation — similar to the way Drush works with Drupal 7. However, Drupal Console takes it a few steps further as it can also generate boilerplate code and also comes packaged with tool to help you convert Drupal 7 modules to work with Drupal 8.

Let’s make the Hello World module, but instead of preparing a module skeleton, we will use Drupal Console to do all of the grunt work for us! First we run `drupal generate:module` in our terminal. From there, a wizard will take over and ask you for the rest of the details.

terminal

That’s it!

terminal

Now you have a module skeleton sitting in `modules/custom/hello_world`.

To finish off the module all we have to do is add the routing file and the basic controller and we are all set.

<?php
/**
* @file
* Contains \Drupal\hello_world\Controller\HelloController.
*/
 
namespace Drupal\hello_world\Controller;
 
use Drupal\Core\Controller\ControllerBase;
 
class HelloController extends ControllerBase {
  public function content() {
    return array(
      '#type' => 'markup',
      '#markup' => $this->t(‘Drupal Console is cool!),
    );
  }
}
?>

hello_world.content:
  path: '/hello'
  defaults:
    _controller: '\Drupal\hello_world\Controller\HelloController::content'
    _title: 'Hello World'
  requirements:
    _permission: 'access content'

Now that our module is ready to go, let's turn it on by running `drupal module:install hello_world`.

successful hello world

Let’s see if it worked!

hello world drupal console worked and is cool

This demonstration didn’t even scratch the surface of what Drupal Console can do. I didn’t even tell you that it works with Drush! (Yes, really. I could have used `drupal drush en hello_world` to enable the module too). So download Drupal Console, it will make things easier.