Basics of D8 Custom Module Development

Drupal 8 is completely based on OOPS. It means there is a lot of difference between D7 and D8 custom development. So today we are going to learn custom module development. There are various changes like now we are going to use Classes, Services, Plugins, Controller etc. There are also directory structure changes.

So let's start with our first custom module in Drupal 8. Create a new directory inside '/modules' directory and name it to your module name. So I am creating a directory 'first_module'. Now our next step is to let Drupal know about our module by creating a '.info.yml' file. Now we have to use '.info.yml' instead of simple '.info' file. Let's create '' file.

name: First D8 Moudle
type: module
description: This is my first D8 module
core: 8.x
package: Sample

Creating a ROUTE

Now our next step is to create a path, so that we can access our newly created page. In D7, we were use 'hook_menu()' to create a new path. But in D8, its replaced by 'routing.yml' file. Let's create our new file 'first_module.routing.yml':

  path: /test/first/module
    _controller: 'Drupal\first_module\Controller\FirstController::firstMethod'
    _permission: 'access content'

When someone access any URL, Drupal then loads the routing file which contains that specific URL.This tells Drupal 8 that a route named 'first_module.test' (named with the module name as prefix) exists and is bound to the URI '/test/first/module' on the site. When that path is accessed, the 'access content' permission is checked on the accessing user and, if access is granted, the 'FirstController::firstMethod' method is invoked and a page is displayed.

Building a page Controller

A Controller is a function that you have to write to perform some task. To create a Controller, you have to create a special directory structure for this. Create a 'src' directory under your root directory of module and then create another directory 'Controller' under 'src' directory.

Now create your Controller PHP Class file as you specified in your routing file. In our case 'FirstController.php':

namespace Drupal\first_module\Controller;

use Symfony\Component\HttpFoundation\Response;

class FirstController {

  public function firstMethod() {
    return new Response('Hello World... My first D8 custom module');