Top 3 Use Cases of Drupal Routing System| Drupal 10

08 / Aug / 2024 by Priya Roy Chowdhury 0 comments

Introduction

Every Drupal developer must experience the Routing in Drupal while creating a seamless interacting website with easy navigation. In this article we will check the different scenarios that we face during the site development phase. I will dive you into the Top 3 interesting and very useful Use cases around the Drupal Routing Systems. But before getting into the details, we will have an overview of the importance of the Drupal Routing System.

Routing System

Drupal Routing System

Drupal Routing System

Overview

Drupal’s routing system is based on Symfony’s routing system. It has all abilities that Symfony routing system have and can have extended functionality as well. Drupal routing uses same syntax as Symfony’s.

What is a Route

A Route in Drupal is not a URL but a configuration that have it’s own set of instructions to display content for a mentioned URL. You can apply access checking and parameter upcasting with custom routes. In Drupal, you can define a route via  <MODULE_NAME>.routing.yml file, which should be kept in the root folder of the respective module.

In this article, we are going to cover the Top 3 Use Cases of Drupal Routing Systems that can be beneficial while developing a similar functionality.

  1. Upcasting dynamic route parameters
  2. What is a ‘route_callbacks’ and how to use 
  3. Call Service class directly from the route

Let’s understand the above points one by one in detail :

1. Upcasting Route Parameters

In Drupal, upcasting involves transforming a route parameter from a basic scalar value, like an ID, into a more intricate object. This allows developers to directly access the full object within the controller, eliminating the need for multiple database queries. Utilizing upcasting for route parameters boosts both the performance and maintainability of Drupal applications.

Implementing Upcasting in Drupal 10

Let’s understand this concept with an example. Here, we have created a route /example/{node} and defined the parameter type as a node entity. So when the user hits a URL like /example/123 in the browser, the node object for node id 123 will load and access the calling controller class to perform the required action.

Step 1: Define the Route with Parameters

First, define a route in your module’s routing file, specifying the parameter you want to upcast.

# example.routing.yml

example.content:
  path: '/example/{node}'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::content'
  requirements:
    _permission: 'access content'
  options:
    parameters:
      node:
        type: entity:node

Step 2: Create the Controller

Next, create the controller that will handle the route. Inject the required services and define the method that will use the upcasted parameter.

namespace Drupal\example\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\node\NodeInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class ExampleController extends ControllerBase {
  public function content(NodeInterface $node) {
    // Your logic here.
    return [
      '#type' => 'markup',
      '#markup' => $this->t('Node title: @title', ['@title' => $node->getTitle()]),
    ];
  }
}

Step 3: Understand the Parameter Conversion

In the above example, the {node} parameter in the route is automatically converted into an NodeInterface object by Drupal. This conversion is made possible by specifying the parameter type in the routing file.

By following the steps outlined in this article, you can implement upcasting effectively and leverage its full potential to create robust and efficient Drupal solutions.

2. What is a ‘route_callbacks’ and How to Use

In Drupal, as we define routes via module.routing.yml files as static routes but we can also implement dynamic routes as per our requirements.

What is route_callbacks?

Dynamic routing in Drupal allows developers to define their own routes dynamically. These dynamic routes are implemented through a method, which is then added as a ‘route_callbacks‘ entry in the modulename.routing.yml file.

Use-Case :

Suppose we have a weather page and on this page every Sunday(Weekly) a new route(link) will be added to display the weekly weather forecast.

To achieve this we can use the Drupal dynamic routing mechanism. we create routes whenever we want to add a new URL with code. By defining a dynamic routing class using route_callbacks and then add the corresponding controller.

2. How to Use route_callbacks in Drupal

Step 1: Define the Route with route_callbacks

First, define the route_callbacks in the module’s routing YML file and specify the callback function.

# example.routing.yml

 route_callbacks:
  - '\Drupal\example\Routing\ExampleRouteCallbacks::routes'

Step 2: Create the Callback Function

Next, you need to create your routing class and the callback function that is responsible for modifying the route and implementing your logic within it. The dynamic routing method should return either an array of \Symfony\Component\Routing\Route objects or a \Symfony\Component\Routing\RouteCollection object.

Example for returning Route object

Create the callback class and define the method to return an array of Route objects. This class should be placed in the src/Routing directory of your module.

namespace Drupal\example\Routing;

use Symfony\Component\Routing\Route;

class ExampleRouteCallbacks {

  public static function routes() {
    // Create the first route.
    $route1 = new Route(
    '/example/dynamic/route1',
    [
      '_controller' => '\Drupal\example\Controller\ExampleController::dynamic',
      '_title' => 'Dynamic Route 1',
    ],
    [
      '_permission' => 'access content'
    ]
    );

    // Create the second route.
    $route2 = new Route(
      '/example/dynamic/route2',
      [
        '_controller' => '\Drupal\example\Controller\ExampleController::dynamic',
        '_title' => 'Dynamic Route 2',
     ],
     ['
       _permission' => 'access content']
    );

    // Return an array of Route objects.
    return [
      'example.dynamic_route1' => $route1,
      'example.dynamic_route2' => $route2,
    ];
  }
}

In the above example, the routes method creates two Route objects and returns them as an array.

Another example to check how can we implement the route method to return a RouteCollection object. This class should be placed in the src/Routing directory of your module.

namespace Drupal\example\Routing;

use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

class ExampleRouteCallbacks {

  public static function routes() {
    $collection = new RouteCollection();
    // Define a new route.
    $route = new Route(
      '/example/dynamic/{id}',
      [
        '_controller' => '\Drupal\example\Controller\ExampleController::dynamic',
        '_title' => 'Dynamic Route Example',
      ],
      [
        '_permission' => 'access content'
      ]
    );

    // Add the new route to the collection.
    $collection->add('example.dynamic_route_with_id', $route);
  return $collection;
 }
}

In the above example here, the route() method creates a new route and adds it to the RouteCollection object. It also modifies an existing route by changing its path.

By following these steps, you can create a dynamic route in Drupal that utilizes route_callbacks to return and modify a RouteCollection object. This approach provides a powerful mechanism for dynamically managing routes within your Drupal application, enhancing flexibility and control.

Grasping and applying ‘route_callbacks’ in Drupal can greatly improve the functionality and security of your Drupal applications. By adhering to best practices and fully utilizing the capabilities of route callbacks, developers can build more dynamic, efficient, and secure web experiences.

3. Call the Service class directly from the route

In Drupal, a service class is a PHP class designed to deliver particular functionalities. These can range from performing database operations to managing user authentication or executing custom business logic. Typically, service classes are registered within Drupal’s service container, which allows them to be accessible throughout the entire application.

Step 1: Setting Up a Service Class in Drupal 10

First, create a class that will serve as your service. This class should contain the methods you wish to call from your routes. The service class file named src/Service/MyCustomService.php , resides in the src folder.

namespace Drupal\mymodule\Service;

class MyCustomService {
  public function myCustomMethod() {
    // Your custom logic here
    return"Hello, this is my custom service method!";
  }
}

Step 2: Register the Service

Next, you need to register this service with Drupal’s service container. This is done in the mymodule.services.yml file within your module.

# mymodule.services.yml
services:
  mymodule.my_custom_service:
   class: 'Drupal\mymodule\Service\MyCustomService'

Step 3: Define the Route

Now, you need to define a route that will call the service method. This is done in the mymodule.routing.yml file.

# mymodule.routing.yml

mymodule.custom_route:
  path: '/custom-route'
  defaults:
   _controller: 'mymodule.my_custom_service:myCustomMethod'
   _title: 'Custom Route'
  requirements:
   _permission: 'access content'

This will execute the myCustomMethod() the method in the class defined is  mymodule.services.yml for the mymodule.my_custom_service service.

Calling a service class directly from the route in Drupal 10 is a powerful technique that can significantly enhance the efficiency and maintainability of your code.

Conclusion

The Routing System in Drupal is fundamental to contemporary Drupal development, providing exceptional flexibility and control over URL mapping and request processing. By mastering this system’s intricacies, developers can build robust, efficient, and secure web applications.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *