Creating your first custom module in Drupal 8 or Drupal 9
Let’s start with creating a simple custom module which will output a text message. We need to create 3 files for this->
a. Info File
b. Routing File
c. Controller
Step 1: Creating the module folder
First we need to create a custom module under [Doc Root]/modules/custom folder. Let us name the folder as first_module.
Step 2: Creating the info file
Let us first create an info file first_module.info.yml which will contain all the information about your custom module.
name: First Moduledescription: First Custom Moduletype: modulecore_version_requirement: 8.x
Step 3: Creating the routing file
Routing file is one of the most important file for Drupal module as it binds the path/URL with the controller. It’s a replacement of hook_menu() which we had in Drupal 7. Let us create a routing file named first_module.routing.yml under the module folder with the below properties.
first_module.welcome:path: '/first/page'defaults:_controller:'Drupal\first_module\Controller\FirstController::firstMethod'_title: 'Welcome to our first Drupal 8 custom module.'requirements:_permission: 'access content'
Step 4: Creating the Controller
As you can see in our earlier step we have already mentioned a controller class named FirstController in the controller properties. So we will create a controller with the same name. First we need to create a folder named “src” under the module folder and then create another folder “Controller” under “src”. Now we will create a controller file named FirstController.php under “Controller” folder. Let us now write a simple code for this controller which will output a message.
<?phpnamespace Drupal\first_module\Controller;use Drupal\Core\Controller\ControllerBase;
class FirstController extends ControllerBase { public function firstMethod() { return array ( '#markup' => 'Welcome to our First Drupal 8 custom Module.' ); }}
Now Login to site and enable the newly created custom module from admin->modules. Now access the path you specified in your routing file, that is /first/page. If you get the ‘Page Not Found’ error, then clear the cache by navigating to admin->configuration->performance. Verify again and it should show the output message as below.