{"id":61960,"date":"2024-08-08T11:10:23","date_gmt":"2024-08-08T05:40:23","guid":{"rendered":"https:\/\/www.tothenew.com\/blog\/?p=61960"},"modified":"2024-08-08T14:22:50","modified_gmt":"2024-08-08T08:52:50","slug":"top-3-use-case-of-drupal-routing-system-drupal-10","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/top-3-use-case-of-drupal-routing-system-drupal-10\/","title":{"rendered":"Top 3 Use Cases of Drupal Routing System| Drupal 10"},"content":{"rendered":"<h2>Introduction<\/h2>\n<p>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.<\/p>\n<h2>Routing System<\/h2>\n<div id=\"attachment_63333\" style=\"width: 635px\" class=\"wp-caption aligncenter\"><img aria-describedby=\"caption-attachment-63333\" decoding=\"async\" loading=\"lazy\" class=\"wp-image-63333 size-large\" src=\"https:\/\/www.tothenew.com\/blog\/wp-ttn-blog\/uploads\/2024\/07\/Screenshot-2024-05-30-at-12.08.30-PM-1-1024x594.png\" alt=\"Drupal Routing System\" width=\"625\" height=\"363\" srcset=\"\/blog\/wp-ttn-blog\/uploads\/2024\/07\/Screenshot-2024-05-30-at-12.08.30-PM-1-1024x594.png 1024w, \/blog\/wp-ttn-blog\/uploads\/2024\/07\/Screenshot-2024-05-30-at-12.08.30-PM-1-300x174.png 300w, \/blog\/wp-ttn-blog\/uploads\/2024\/07\/Screenshot-2024-05-30-at-12.08.30-PM-1-768x446.png 768w, \/blog\/wp-ttn-blog\/uploads\/2024\/07\/Screenshot-2024-05-30-at-12.08.30-PM-1-624x362.png 624w, \/blog\/wp-ttn-blog\/uploads\/2024\/07\/Screenshot-2024-05-30-at-12.08.30-PM-1.png 1392w\" sizes=\"(max-width: 625px) 100vw, 625px\" \/><p id=\"caption-attachment-63333\" class=\"wp-caption-text\">Drupal Routing System<\/p><\/div>\n<h2>Overview<\/h2>\n<p>Drupal&#8217;s routing system is based on <strong><a href=\"https:\/\/symfony.com\/doc\/current\/routing.html\">Symfony&#8217;s routing system<\/a>. <\/strong>It has all abilities that Symfony routing system have and can have extended functionality as well. Drupal routing uses same syntax as Symfony&#8217;s.<\/p>\n<h2><strong>What is a Route<\/strong><\/h2>\n<p>A Route in Drupal is not a URL but a configuration that have it&#8217;s own set of instructions to display content for a mentioned URL. You can apply <em>access checking<\/em>\u00a0and\u00a0<em>parameter upcasting with custom routes. In Drupal, you can define a route via \u00a0&lt;MODULE_NAME&gt;.routing.yml file, which should be kept in the root folder of the respective module.<\/em><\/p>\n<p>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.<\/p>\n<ol class=\"ul1\">\n<li class=\"li1\">Upcasting dynamic route parameters<\/li>\n<li class=\"li1\">What is a \u2018route_callbacks&#8217;\u00a0and how to use<span class=\"Apple-converted-space\">\u00a0<\/span><\/li>\n<li class=\"li1\">Call Service class directly from the route<\/li>\n<\/ol>\n<p>Let&#8217;s understand the above points one by one in detail :<\/p>\n<h3>1. <span style=\"text-decoration: underline;\">Upcasting Route Parameters<\/span><\/h3>\n<p>In Drupal, <strong>upcasting<\/strong> 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.<\/p>\n<h3>Implementing Upcasting in Drupal 10<\/h3>\n<p>Let&#8217;s understand this concept with an example. Here, we have created a route <strong>\/example\/{node} <\/strong>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.<\/p>\n<h3>Step 1: Define the Route with Parameters<\/h3>\n<p>First, define a route in your module\u2019s routing file, specifying the parameter you want to upcast.<\/p>\n<p># example.routing.yml<\/p>\n<div>\n<pre>example.content:\r\n  path: '\/example\/{node}'\r\n  defaults:\r\n    _controller: '\\Drupal\\example\\Controller\\ExampleController::content'\r\n  requirements:\r\n    _permission: 'access content'\r\n  options:\r\n    parameters:\r\n      node:\r\n        type: entity:node<\/pre>\n<\/div>\n<h3>Step 2: Create the Controller<\/h3>\n<p>Next, create the controller that will handle the route. Inject the required services and define the method that will use the upcasted parameter.<\/p>\n<pre>namespace Drupal\\example\\Controller;\r\n\r\nuse Drupal\\Core\\Controller\\ControllerBase;\r\nuse Drupal\\node\\NodeInterface;\r\nuse Symfony\\Component\\DependencyInjection\\ContainerInterface;\r\n\r\nclass ExampleController extends ControllerBase {\r\n  public function content(NodeInterface $node) {\r\n    \/\/ Your logic here.\r\n    return [\r\n      '#type' =&gt; 'markup',\r\n      '#markup' =&gt; $this-&gt;t('Node title: @title', ['@title' =&gt; $node-&gt;getTitle()]),\r\n    ];\r\n  }\r\n}<\/pre>\n<h3>Step 3: Understand the Parameter Conversion<\/h3>\n<p>In the above example, the <code>{node}<\/code> parameter in the route is automatically converted into an <code>NodeInterface<\/code> object by Drupal. This conversion is made possible by specifying the parameter type in the routing file.<\/p>\n<p>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.<\/p>\n<h3>2. <span style=\"text-decoration: underline;\">What is a \u2018route_callbacks&#8217; and How to Use<\/span><\/h3>\n<p>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.<\/p>\n<h3>What is route_callbacks?<\/h3>\n<p>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 &#8216;<strong>route_callbacks<\/strong>&#8216; entry in the modulename.routing.yml file.<\/p>\n<h3>Use-Case :<\/h3>\n<p>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.<\/p>\n<p>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.<\/p>\n<h3>2. <span style=\"text-decoration: underline;\">How to Use route_callbacks in Drupal<\/span><\/h3>\n<h3>Step 1: Define the Route with route_callbacks<\/h3>\n<p>First, define the route_callbacks in the module&#8217;s routing YML file and specify the callback function.<\/p>\n<p># example.routing.yml<\/p>\n<pre> route_callbacks:\r\n  - '\\Drupal\\example\\Routing\\ExampleRouteCallbacks::routes'<\/pre>\n<h3>Step 2: Create the Callback Function<\/h3>\n<p>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 <strong>\\Symfony\\Component\\Routing\\Route<\/strong> objects or a \\Symfony\\Component\\Routing\\RouteCollection object.<\/p>\n<p>Example for returning Route object<\/p>\n<p>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.<\/p>\n<div>\n<pre>namespace Drupal\\example\\Routing;\r\n\r\nuse Symfony\\Component\\Routing\\Route;\r\n\r\nclass ExampleRouteCallbacks {\r\n\r\n  public static function routes() {\r\n    \/\/ Create the first route.\r\n    $route1 = new Route(\r\n    '\/example\/dynamic\/route1',\r\n    [\r\n      '_controller' =&gt; '\\Drupal\\example\\Controller\\ExampleController::dynamic',\r\n      '_title' =&gt; 'Dynamic Route 1',\r\n    ],\r\n    [\r\n      '_permission' =&gt; 'access content'\r\n    ]\r\n    );\r\n\r\n    \/\/ Create the second route.\r\n    $route2 = new Route(\r\n      '\/example\/dynamic\/route2',\r\n      [\r\n        '_controller' =&gt; '\\Drupal\\example\\Controller\\ExampleController::dynamic',\r\n        '_title' =&gt; 'Dynamic Route 2',\r\n     ],\r\n     ['\r\n       _permission' =&gt; 'access content']\r\n    );\r\n\r\n    \/\/ Return an array of Route objects.\r\n    return [\r\n      'example.dynamic_route1' =&gt; $route1,\r\n      'example.dynamic_route2' =&gt; $route2,\r\n    ];\r\n  }\r\n}<\/pre>\n<\/div>\n<p>In the above example, the routes method creates two Route objects and returns them as an array.<\/p>\n<p>Another example to check how can we implement the route method to return\u00a0a <strong>RouteCollection<\/strong> object. This class should be placed in the src\/Routing directory of your module.<\/p>\n<pre>namespace Drupal\\example\\Routing;\r\n\r\nuse Symfony\\Component\\Routing\\Route;\r\nuse Symfony\\Component\\Routing\\RouteCollection;\r\n\r\nclass ExampleRouteCallbacks {\r\n\r\n  public static function routes() {\r\n    $collection = new RouteCollection();\r\n    \/\/ Define a new route.\r\n    $route = new Route(\r\n      '\/example\/dynamic\/{id}',\r\n      [\r\n        '_controller' =&gt; '\\Drupal\\example\\Controller\\ExampleController::dynamic',\r\n        '_title' =&gt; 'Dynamic Route Example',\r\n      ],\r\n      [\r\n        '_permission' =&gt; 'access content'\r\n      ]\r\n    );\r\n\r\n    \/\/ Add the new route to the collection.\r\n    $collection-&gt;add('example.dynamic_route_with_id', $route);\r\n  return $collection;\r\n }\r\n}<\/pre>\n<p>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.<\/p>\n<p>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.<\/p>\n<p>Grasping and applying &#8216;route_callbacks&#8217; 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.<\/p>\n<h3>3. <span style=\"text-decoration: underline;\">Call the Service class directly from the route<\/span><\/h3>\n<p>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&#8217;s service container, which allows them to be accessible throughout the entire application.<\/p>\n<h3>Step 1: Setting Up a Service Class in Drupal 10<\/h3>\n<p>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.<\/p>\n<div>\n<pre>namespace Drupal\\mymodule\\Service;\r\n\r\nclass MyCustomService {\r\n  public function myCustomMethod() {\r\n    \/\/ Your custom logic here\r\n    return\"Hello, this is my custom service method!\";\r\n  }\r\n}<\/pre>\n<\/div>\n<h3>Step 2: Register the Service<\/h3>\n<p>Next, you need to register this service with Drupal&#8217;s service container. This is done in the <code>mymodule.services.yml<\/code> file within your module.<\/p>\n<div># mymodule.services.yml<\/div>\n<div>\n<pre>services:\r\n  mymodule.my_custom_service:\r\n   class: 'Drupal\\mymodule\\Service\\MyCustomService'<\/pre>\n<\/div>\n<h3>Step 3: Define the Route<\/h3>\n<p>Now, you need to define a route that will call the service method. This is done in the <code>mymodule.routing.yml<\/code> file.<\/p>\n<p># mymodule.routing.yml<\/p>\n<div>\n<pre>mymodule.custom_route:\r\n  path: '\/custom-route'\r\n  defaults:\r\n   _controller: 'mymodule.my_custom_service:myCustomMethod'\r\n   _title: 'Custom Route'\r\n  requirements:\r\n   _permission: 'access content'\r\n<\/pre>\n<\/div>\n<p>This will execute the myCustomMethod<code class=\" language-php\"><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><\/code> the method in the class defined is\u00a0 <code>mymodule.services.yml<\/code> for the mymodule.my_custom_service\u00a0service.<\/p>\n<p>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.<\/p>\n<h3>Conclusion<\/h3>\n<p>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&#8217;s intricacies, developers can build robust, efficient, and secure web applications.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>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. [&hellip;]<\/p>\n","protected":false},"author":1508,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":90},"categories":[3602],"tags":[4862,6210,1610],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/61960"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/1508"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=61960"}],"version-history":[{"count":23,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/61960\/revisions"}],"predecessor-version":[{"id":63900,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/61960\/revisions\/63900"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=61960"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=61960"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=61960"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}