Defining a controller to provide a custom page
Whenever an HTTP request is made to a Drupal site, the path for the URL is routed to a controller. Controllers are responsible for returning the response for a path that has been defined as a route. Generally, these controllers return render arrays for Drupal’s render system to convert into HTML.
In this recipe, we will define a controller that returns a render array to display a message on the page.
How to do it…
- First, we need to create the
src/Controllerdirectory in the module’s directory. We will put our controller class in this directory, which gives ourcontrollerclass theControllernamespace:mkdir -p src/Controller
- Create a file named
HelloWorldController.phpin the controller directory. This will hold ourHelloWorldControllercontroller class. - Our
HelloWorldControllerclass will extend theControllerBasebase class provided by Drupal core:<?php
namespace Drupal\mymodule\Controller...