John
John John has been developing websites and software for over 20 years. Focusing on Drupal over the last 12 years.

Drupal 8: Goodbye hook_menu!

Drupal 8: Goodbye hook_menu!

So, as you may be aware, hook_menu no longer exists in Drupal 8, replaced by a much better routing system. This new system consists of various different YAML files, to determine the route and the Controller to be used.

So, rather than defining routes in hook_menu in Drupal 7, they are now defined in module.routing.yml files.

Differences

Drupal 7

function mymodule_menu() {
  $items['mymodule/export/%/%'] = array(
    'page callback' => 'mymodule_export',
    'page arguments' => array(2, 3),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    'file' => 'mymodule.pages.inc',
  );

  $items['node/%node/outline'] = array(
    'title' => 'Outline',
    'page callback' => 'mymodule_outline',
    'page arguments' => array(1),
    'access callback' => '_mymodule_outline_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 2,
    'file' => 'mymodule.pages.inc',
  );

  return $items;
}

Drupal 8

mymodule.content:
  path: '/some-content'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyModuleController::content'
    _title: 'Here is some content'
  requirements:
    _permission: 'access content'

So in the Drupal 8 example we are creating a route called mymodule.content which will allow users to visit a page on your site with a path of /some-content and see some content. When a user visits this link it will invoke a method called content inside your MyModuleController file and return some markup.

So, here is an example of what our controller would look like. Drupal 8 supports PSR-4 so the class needs to be placed in mymodule/src/Controller directory with a name of MyModuleController.php

<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Controller description.
 */
class MyModuleController extends ControllerBase {

  public function content() {
    return [
      '#markup' => $this->t('Here is some content.'),
    ];
  }
}

Controllers can also be used in other ways, like updating data via AJAX calls. I will expand on this in future articles.

Please leave a comment with any feedback or if you feel I have explained something incorrectly.

comments powered by Disqus