Mastering Routes and Controllers in Drupal
In Drupal development, understanding how routes and controllers work together is crucial for managing requests and generating responses effectively.
Link to the-router headingThe Router
The router in Drupal determines which code should run when a specific URI is requested. It maps a URI to a controller, defining how Drupal handles that URI. Routes are defined in a YAML file located in the root of your module using a specific naming convention: modulename.routing.yml.
For example, if you have a module named welcome, the route file would be welcome.routing.yml. Inside this file, you would find the following code:
welcome.welcome_controller_welcome:
path: '/welcome'
defaults:
_controller: '\Drupal\welcome\Controller\WelcomeController::welcome'
_title: 'Welcome Controller'
requirements:
_permission: 'access content'Breaking down each part:
- Route Name:
welcome.welcome_controller_welcome– This consists of the module name, the controller, and the method handling the request. - Path:
'/welcome'– This is the URI that maps to the controller. - Defaults:
_controller: The path to the controller class and method._title: The title of the page.
- Requirements:
_permission– Specifies the permission needed to access this route.
The Controller
Controllers in Drupal take requests and decide how to handle them. For the welcome module, the controller responsible for generating the content is defined in WelcomeController.php located in the src/Controller directory.
The controller class might look like this:
namespace Drupal\welcome\Controller;
use Drupal\Core\Controller\ControllerBase;
class WelcomeController extends ControllerBase {
/**
* Welcome.
*
* @return array
* Return a renderable array.
*/
public function welcome() {
return [
'#type' => 'markup',
'#markup' => $this->t('Welcome to my site')
];
}
}Key points about the controller:
- Namespace and Use Statements: These organize your classes and ensure no conflicts with other classes having the same name.
- Class and Method:
WelcomeControllerextendsControllerBase, and thewelcome()method returns a renderable array. The route maps the URI/welcometo this method.
To see the changes reflected on your site, such as modifying the welcome message, you need to rebuild the cache:
$ drupal cache:rebuildRevisiting the /welcome page will now display the updated message. Understanding these fundamental components of Drupal will help you manage content and functionality more effectively in your projects.