Module Development

Use a Service in a Controller for Drupal 8, 9, 10, and 11

Controllers in Drupal frequently need to use services to figure out what information to display on the page. This might include querying for a list of entities, getting information about the current user, or accessing saved configuration. It's a best practice to always use dependency injection to supply services to a controller. In the anytown module we can improve the WeatherPage controller by making it access a weather forecast API to get up-to-date data.

In this tutorial, we'll:

  • Set up a mock weather forecast API.
  • Refactor our WeatherPage controller to inject the http_client and logger.factory services.
  • Update the build() method of our controller to use the provided services to get and display a weather forecast.

By the end of this tutorial you should be able to use dependency injection to give a controller in a Drupal module the services it requires, and then make use of those services in building the page content.

Drupal Module Developer Guide