Drupal8 route controller

In real life what we understand about Routing – this is nothing but the perfect way to select the exact path to execute any process/function. If we want to relate the routing with Drupal then how it will look. Nothing to worry, its already in Drupal setup. In Drupal 7 the Routing is handled through hook_menu(), but in this article we will get to know how the Routing handle by routing.yml file in Drupal 8. If we want to work with hook_menu() in Drupal 8 then we have to create a “module_name.routing.yml” file in your Module directory. So lets check with an example:

Example to use hook_menu() in Drupal 7:

If we create a custom module in Drupal 7 then we create 3 file in module directory, these are “modulle_name.info”, “modulle_name.module” and “modulle_name.inc”. In the “modulle_name.module” file we use the hook_menu(). Below is an example of a hook_menu().


function hello_menu() {
 return array(
 'hello' => array(
  'title' => 'Hello',
  'page callback' => 'hello_page',
  'access callback' => 'TRUE',
  'file' => 'hello.inc',

In Drupal 7, hook_menu() did two things:

  1. It create a menu with appropriate name and added a link/path to the menu ( e.g. the ‘ title ’ key provides the menu title of that ‘hello’ link ).
  2. It defined what happens when we visit that URL ( e.g. the ‘ page callback ’ key. The ‘hello_page‘ is a name of a function. the function will be define what happens when we visit in the URL ).

Example to use hook_menu() in Drupal 8:

In Drupal 8 we break the “.module” file in two different files “.module” and “.routing.yml”. Mainly we divide the work of “hook_menu” in those two files.


 function hello_menu(){
 return array(
  'hello' => array(
  'title' => 'Hello',
  'route_name' => 'hello',
  'menu_name' => 'main'


 path: '/hello'
  _content: 'Path_of_PHP_class :: Method_of_PHP_class'
  _permission: 'TRUE'

In Drupal 8 the “hook_menu()” only for added a link to that URL in an appropriate menu and the “.routing.yml” handles that what happens when we visit that URL.

Contents of hello.routing.yml:

  • Every route have a unique name for identify the route. In the first line the “hello:” is the unique name for this route.
  • The second line is for the path of URL. When the respective menu will click then a new page will open and the URL will be previous URL + the path content.
  • The “defaults:“ section lets us specify a special variable “_content”. That variable refer the PHP class and the method of the PHP class that will be called when this route fires. For the “_content” key the Drupal know that the returned value from our PHP class is going to be the content for the main part of the page.
  • The “requirements:” section is the replacement of the “’access callback’ => ‘TRUE’”. If the “_permission:” of the section is true then the PHP class invoke.

Hope this will help you, any suggestion will be warmly accepted.