Module Development

Define a Weather Forecast Service for Drupal 8, 9, and 10

The logic for retrieving and processing a weather forecast is hard-coded into the WeatherPage controller. To make our code more reusable, maintainable, and organized, we can refactor this code into a custom weather forecast API service.

In this tutorial, we'll:

  • Define a PHP interface for a weather forecast API service and write an implementation of that service.
  • Create a service definition file to inform Drupal about our new service and its dependencies.
  • Refactor the WeatherPage controller to use the new service, which will clean up duplicate code.

By the end of this tutorial, you'll be able to define and use a custom service in a Drupal module.

Drupal Module Developer Guide