In Drupal – 8 most of the Hooks such as hook_init, hook_boot are removed from the Drupal 8.
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.
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
KernelEvents::RESPONSE
KernelEvents::TERMINATE
KernelEvents::VIEW
How to create an Event Subscriber?
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
services:
customredirect_event_subscriber:
class: Drupal\custom_eventsubscriber\EventSubscriber\ExampleeventSubscriber
tags:
- {name: event_subscriber}
<?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:
Post a Comment