Change record status: 
Project: 
Introduced in branch: 
8.x
Description: 

As of Drupal 8, hook_init() no longer exists, since, after introducing the Symfony kernel and events it was not serving any specific need.

  • If your module needs to perform changes on the request/response object very early to the request an event subscriber should be used listening to the kernel.request event.

    D7:

    <?php
    function mymodule_init() {
      if (!empty(
    $_GET['redirect-me'])) {
       
    drupal_goto('http://example.com/');
      }
    }
    ?>

    D8:
    Register your Event Subscriber in your mymodule.services.yml and tag it as such:

    services:
      mymodule_event_subscriber:
        class: Drupal\mymodule\EventSubscriber\MymoduleSubscriber
        tags:
          - {name: event_subscriber}

    Your MymoduleSubscriber should implement the EventSubscriberInterface interface and in its getSubscribedEvents() point to the method that should be executed:

    <?php
    namespace Drupal\mymodule\EventSubscriber;
    use
    Symfony\Component\HttpFoundation\RedirectResponse;
    use
    Symfony\Component\HttpKernel\KernelEvents;
    use
    Symfony\Component\HttpKernel\Event\GetResponseEvent;
    use
    Symfony\Component\EventDispatcher\EventSubscriberInterface;
    class
    MymoduleSubscriber implements EventSubscriberInterface {
      public function
    checkForRedirection(GetResponseEvent $event) {
        if (
    $event->getRequest()->query->get('redirect-me')) {
         
    $event->setResponse(new RedirectResponse('http://example.com/'));
        }
      }
     
    /**
       * {@inheritdoc}
       */
     
    static function getSubscribedEvents() {
       
    $events[KernelEvents::REQUEST][] = array('checkForRedirection');
        return
    $events;
      }
    }
    ?>
  • If your module just needs to add css and/or javascript, hook_page_build should be used instead
Impacts: 
Module developers
Updates Done (doc team, etc.)
Online documentation: 
Not done
Theming guide: 
Not done
Module developer documentation: 
Not done
Examples project: 
Not done
Coder Review: 
Not done
Coder Upgrade: 
Not done
Other: 
Other updates done

Comments

Yay, now Drupal developers will need to use an IDE to generate boilerplate code just like Java programmers :/