Create own custom module on drupal 8

Module creation on drupal 8 is an eight step process. Suppose create a module named as "Custom module" that passes through following set of steps:

1) Create a new folder named as "custom_module"  in /modules folder of drupal 8.

 

 

2) Create a new file named as "custom_module.info.yml" in the /modules/custom_module folder.

 

 

3) Open "custom_module.info.yml" file and put following code in it.

 

name: Custom module
type: module
package: Custom
description: 'It is my first drupal 8 custom module.'
core: 8.x

 

In the above code, name shows the name of module, type tells that code is about a module, package shows the name of package in which module resides, description gives a little bit information about module and eventually core shows the drupal version.

 

4) Create a new file named as "custom_module.module" in the /modules/custom_module folder. Keep this file empty.

 

 

5) Create a new file named as "custom_module.routing.yml" in the /modules/custom_module folder.

 

 

6) Open "custom_module.routing.yml" file and put following code in it.

 

custom_module.content:
  path: '/custommodule'
  defaults:
    _controller: '\Drupal\custom_module\Controller\CustomController::content'
    _title: 'Custom Text'
  requirements:
    _permission: 'access content'

 

In the above code, custom_module.content: shows that information about content of module is given here, path: shows the path of module content page, _controller: shows the path of function being called on content page, _title: shows the title of content page,  permission: shows the roles that are permitted to access content

 

7) Create a new file named as "CustomController.php" in /modules/custom_module/src/Controller folder. The folders "src" and "Controller" are required to outoload the Controller class otherwise Controller class code is needed to embed explicitly.

 

 

8) Open "CustomController.php" file and put following code in it.

 

<?php
/**
 * @file
 * Contains \Drupal\custom_module\Controller\CustomController.
 */

namespace Drupal\custom_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class CustomController extends ControllerBase {
  public function content() {
    return array(
        '#type' => 'markup',
        '#markup' => $this->t('This is my custom text.'),
    );
  }
}
?>

 

In the above code, keyword "namespace" is used for each class that distints a class of same name from other. The keyword "use" tells about the path of ControllerBase class file. The CustomController class extends the ControllerBase class and calls content() function that returns text of "This is my custom text."