hook_init() in Drupal 8

In Drupal – 8 most of the Hooks such as hook_init, hook_boot are removed from the Drupal 8.

These Hooks are replaced with Event Subscriber in Drupal 8. If you are performing few actions such as redirect, add CSS, add JS or any other modification on request, it can be done by registering Event Subscriber.

As we know Drupal 8 introduces Symfony Event Components and includes many Symfony components in Drupal 8 Core. In future versions of Drupal 8, Symfony Events will play a vital role and will enhance the website performance, functionality.

How does it work in Drupal 8 now?

Drupal 8 has adopted symfony as a part of its core. It uses Symfony kernel and events to do the same now. List of kernel events available in Drupal 8 are as follows:

KernelEvents::CONTROLLER

The CONTROLLER event occurs once a controller was found for handling a request.

KernelEvents::EXCEPTION

The EXCEPTION event occurs when an uncaught exception appears.

KernelEvents::FINISH_REQUEST

The FINISH_REQUEST event occurs when a response was generated for a request.

KernelEvents::REQUEST

The REQUEST event occurs at the very beginning of request dispatching.

KernelEvents::RESPONSE

The RESPONSE event occurs once a response was created for replying to a request.

KernelEvents::TERMINATE

The TERMINATE event occurs once a response was sent.

KernelEvents::VIEW

The VIEW event occurs when the return value of a controller is not a Response instance.

Drupal 8 provides a way to subscribe to all these events and attach callbacks to be executed when these events occur. If our module needs to perform changes on the request/response object very early to the request an event subscriber should be used listening to the

KernelEvents::REQUEST event. Same goes for the other events as well.

How to create an Event Subscriber?

The example below shows a Drupal 7 hook_init() implementation which appends Access-Control-Allow-Origin to the response headers to allow CORS(Cross Origin Resource Sharing).

mymodule.module
/**
 * Implements hook_init()
 */
function mymodule_init() {
  drupal_add_http_header('Access-Control-Allow-Origin', '*', TRUE);
}

Steps to convert hook_init into an event subscriber in Drupal 8


1. Create a new Service for Event Subscriber
2. Attach a callback to the KernelEvents::RESPONSE event in Event Subscriber Class.
3. the above code inside the attached callback function.

Creating a new service
Create a yml file custom_eventsubscriber.services.yml as follows:(custom_eventsubscriber is module Name)

services:
    customredirect_event_subscriber:
        class: Drupal\custom_eventsubscriber\EventSubscriber\ExampleeventSubscriber
        tags:
            - {name: event_subscriber}

Create a ExampleeventSubscriber.php file in src/EventSubscriber folder and paste the following code:

<?php
namespace Drupal\custom_eventsubscriber\EventSubscriber;
 
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Drupal\Core\Url;
/**
 * Redirect .html pages to corresponding Node page.
 */
 class ExampleeventSubscriber implements EventSubscriberInterface {
 
  /** @var int */
  private $redirectCode = 301;
 
  /**
   * Redirect pattern based url
   * @param GetResponseEvent $event
   */
  public function addAccessAllowOriginHeaders(GetResponseEvent $event) {
    //echo "hello";
	//die;
    //$request = \Drupal::request();
    //$requestUrl = $request->server->get('REQUEST_URI', null);
    //echo $requestUrl;
	//die;
      $response= $event->getResponse();
      $response->headers->set('Access-Control-Allow-Origin', '*');
  }
 
  /**
   * Listen to kernel.request events and call addAccessAllowOriginHeaders
.
   * {@inheritdoc}
   * @return array Event names to listen to (key) and methods to call (value)
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = array('addAccessAllowOriginHeaders');
    return $events;
  }
}
?>

No comments:

Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...