Creating a simple Hello module in Drupal 8

posted in: Drupal | 0

Drupal 8 is has many advanced CMS features with using the most advanced features of PHP language and integrates number of third party libraries.  Drupal 8 makes use of OOP concepts heavily while using PHP classes, objects, namespaces and many design patterns using these.  Symfony is a PHP framework that Drupal borrows from in order to reduce code duplication across various PHP projects. Much of the code that Drupal 8 uses to handle routing, sessions and the services container, amongst other things, is borrowed from Symfony. Drupal 8 makes use of PHP annotations — @docblock comments added to your code using a special syntax — for plugin discovery and to provide additional context/meta-data for code that’s being executed.

 

Let us create our first module in Drupal 8 using the following steps.

  1. Create folder with module machine name in the sites/all/modules directory or modules/custom directory. I’m creating a hello_world module , I created it in the modules/custom directory.
  2. Let Drupal 8 know about your module with an .info.yml file. I have created hello_world.info.yml file. Following are its contents.
    name: Hellow World Module
    description: Creates module to display Hellow WOrld on a page
    core: 8.x
    package: custom
    type: module
    version: 1.0
    php: 5.6

    We should add the name and description. Also need to define core and type. Also it needs to define the version and optionally minimum php version needed too.

  3. Let Drupal 8 know the paths by .routing.yml file. It maps the path and and code that gets executed when that path is accessed.
    hello_world.hello:
        path: '/hello'
        defaults:
            _controller: Drupal\hello_world\Controller\HelloController::hello
            _title: 'This is title from router'
        requirements:
            _permission: 'access content'

     

  4. Next we need to add the controller class which has the code that is executed when the path is accessed.
    <?php
    
    namespace Drupal\hello_world\Controller;
    
    use Drupal\Core\Controller\ControllerBase;
    
    class HelloController extends ControllerBase {
    
        public function content() {
            return [
                "#type" => 'markup',
                '#markup' => $this->t("This is a content added")
            ];
        }
    
        public function hello() {
            return [
                '#type' => 'markup',
                '#markup' => 'This is another content to hello'
            ];
        }
    
    }

     

  5. After writing above code and if you visit your modules page in Drupal 8 , you’ll see your module listed. Enable the module and visit /hello you’ll see the output as defined by the controller.

 

This is the simple way that can be used to create a module in Drupal 8.

 

Leave a Reply