Drupal - Is hook_init() still used? If it is not anymore used, how do I convert code implementing hook_init()?

Perhaps this has changed since this question was last answered. But I think the preferred approach to replacing what is going on in hook_init is to create an event subscriber, and adding to the 'request'. Here is how you do that for those that may find it useful.

Example services.yml

services:
  init_subscriber:
    class:   Drupal\mymodule\EventSubscriber\MyModuleSubscriber
    arguments: ['@current_user'] // <- optional args
    tags:
      - {name: event_subscriber} // <- Required Tag

Then you would implement the EventSubscriberInterface (new file in the src/EventSubscriber directory) and in the implemented method getSubscribedEvents you can do something like...

/**
 * {@inheritdoc}
 */
public static function getSubscribedEvents() {
  $events[KernelEvents::REQUEST][] = array('initializeMyModule');
  return $events;
}

And add the method accordingly

/**
 * MyModule
 *
 * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
 *   The event to process.
 */
public function initializeMyModule(GetResponseEvent $event) {
  $request = $event->getRequest();   
  ...
}

Yes, hook_init() is not used in Drupal 8. If you need drupal_add_js() or drupal_add_css() you can use hook_page_build() instead (note: this hook was removed in Drupal 8.0.0-beta3 see change record), which is also useful for that in Drupal 7.

For example, CSS styles and JavaScript code can be added to hook_page_build() using $page['#attached'].

 $path = drupal_get_path('module', 'MY_MODULE');
 $page['#attached']['js'][$path . '/my_module.js'] = array('scope' => 'footer');
 $page['#attached']['css'][$path . '/my_module.base.css'] = array('every_page' => TRUE);

If you need to do more complex listening on the request/response there, you can define a Drupal 8 style kernel event listener as documented on hook_init() removed.


hook_page_build() has been deprecated in favor of hook_page_attachments() change record here.

Example:

function MYMODULE_page_attachments(array &$attachments) {
  $attachments ['#attached']['library'][] = 'modulename/libraryname';
}

libraryname is the name of the library, defined in your module's mymodule.libraries.yml

Tags:

8

Hooks