Module Development

Create a Route and Controller for Drupal 8, 9, 10, and 11

If you want to define a new URL that a user can navigate to, and custom PHP code that will generate the content of the page, you need a route and a controller. Most of the time you'll want to do something more complex than hard code the content of the page. This will require using services in your controller. This can be accomplished in different ways.

In this tutorial we'll:

  • Provide the definition for a new route which maps a path to the callback method of a controller class.
  • Create a controller that returns a hard coded string.
  • Look at examples of using both ControllerBase and dependency injection to access services from a controller, and discuss the benefits of both approaches.

By the end of this tutorial, you should be able to define a new route that maps to a controller and displays content on the page as a result of your custom logic.