How to Use Hook_init in Drupal 8?

10 / Jan / 2017 by Jeet Lal 0 comments

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 etc.

Available Events in Drupal 8
Symfony 2 framework are included in Drupal 8 core. Drupal 8 uses Symfony Event Components to do the same. Following kernel events are available in Drupal 8:

  • 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.

How to create Module using Events Subscriber in Drupal 8?

I am creating a custom redirect module and redirecting the pattern based URL to new URL. For example : http://www.test.com/about_us.html to http://www.test.com/about-us.
Module name : customerredirect

Steps 1: Create a custom redirect folder in the modules folder.
Steps 2: Create readme.md file that will have introduction,requirements,recommended modules and etc about module.
Steps 3: Create customredirect.info.yml file that will have information about module like name, type, package, version etc.
Steps 4: Create customredirect.routing.yml file and add routing for this module.
Steps: 5: Create customredirect.services.yml files and define the required services.
Steps 6: Create a src/EventSubscriber folder.
Steps 7: Open customredirect.info.yml file and paste the below code:

[php]
name: Customredirect
type: module
description: ‘Custom redirect module’
package: Custom
version: ‘8.1.0’
core: 8.x
[/php]

Steps 8: Open customredirect.routing.yml and add below code:

[php]
customredirect.render:
requirements:
_permission: ‘access content’
[/php]

I have added only the access permission because there is no menu for this module in admin.

Steps 9: Open customredirect.services.yml file and add below code:

[php]
services:
customredirect_event_subscriber:
class: Drupal\customredirect\EventSubscriber\CustomredirectSubscriber
tags:
– {name: event_subscriber}
[/php]

Note: Annotation should be proper because it follows the Symfony annotation mechanism to read configuration.

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

[php]
namespace Drupal\customredirect\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 CustomredirectSubscriber implements EventSubscriberInterface {

/** @var int */
private $redirectCode = 301;

/**
* Redirect pattern based url
* @param GetResponseEvent $event
*/
public function customRedirection(GetResponseEvent $event) {

$request = \Drupal::request();
$requestUrl = $request->server->get(‘REQUEST_URI’, null);

/**
* Here i am redirecting the about-us.html to respective /about-us node.
* Here you can implement your logic and search the URL in the DB
* and redirect them on the respective node.
*/
if ($requestUrl==’/about-us.html’) {
$response = new RedirectResponse(‘/about-us’, $this->redirectCode);
$response->send();
exit(0);
}
}

/**
* Listen to kernel.request events and call customRedirection.
* {@inheritdoc}
* @return array Event names to listen to (key) and methods to call (value)
*/
public static function getSubscribedEvents() {
$events[KernelEvents::REQUEST][] = array(‘customRedirection’);
return $events;
}
}
[/php]

Conclusion: In Drupal 8, we can use Event Subscriber to replace hook_init or hook_boot and achieve the same functionality that was done by hook_init or hook_boot in Drupal 7.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *