Module Development

Create a Controller for the Weather Page for Drupal 8, 9, and 10

We need a place to put the custom PHP code for our /weather page. In Drupal, controllers encapsulate the custom PHP logic that generates the content of a page. A basic controller might output a hard-coded response, or perform a simple calculation in PHP. Complex controllers make database requests, query third-party APIs, and format complex data using injected services and custom PHP logic.

In this tutorial, we'll:

  • Create a new controller class following the PSR-4 standard.
  • Define the Drupal\anytown\Controller\WeatherPage class with a build() method that returns the page's content.
  • Verify that our route and controller are working.

By the end of this tutorial, you should be able to navigate to /weather in your browser and see the output from our custom controller.

Drupal Module Developer Guide