10

Looking on Drupal.org API, I noticed that hook_init() is not documented for Drupal 8. Looking at the change records, I found Bootstrap hooks no longer exist, which points to Get rid of all 'bootstrap' hooks, where the bootstrap hooks are said to be hook_boot() and hook_exit(); nothing is said about hook_init().

I searched for hook_init in Drupal 8 source, and I found the following code. The first one is a reference to hook_init() made in a comment; the other two seem a hook_init() implementation, but they both get a parameter I am not expecting.

function overlay_enable() {
  if (strpos(current_path(), 'admin/modules') === 0) {
    // Flag for a redirect to <front>#overlay=admin/modules on hook_init().
    $_SESSION['overlay_enable_redirect'] = 1;
  }
}
/**
 * Implements hook_init().
 */
function phptemplate_init($template) {
  $file = dirname($template->filename) . '/' . $template->name . '.theme';
  if (file_exists($file)) {
    include_once DRUPAL_ROOT . '/' . $file;
  }
}
/**
 * Implements hook_init().
 */
function twig_init($template) {
  $file = dirname($template->filename) . '/' . $template->name . '.theme';
  if (file_exists($file)) {
    include_once DRUPAL_ROOT . '/' . $file;
  }
}

I also looked for any function invoking hook_init() but I didn't find any.

How do I convert Drupal 7 code implementing hook_init() to code running on Drupal 8/9?

0

3 Answers 3

7

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();   
  ...
}
2
  • How to use ['#attached]['js] in function initializeMyModule? SInce there is no $var, $page or somether argument in the function.
    – neha
    Aug 9, 2016 at 11:20
  • @neha – You don't. This answer copes with how to replace hook init for more advanced stuff. But for attaching libraries you use hook_page_attachments or hook_page_attachments_alter.
    – leymannx
    Aug 12, 2019 at 10:52
5

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, 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, you can define an event listener as documented on hook_init() removed.

1
  • 2
    Appears that hook_page_build isn't a thing in D8 anymore? Jan 22, 2016 at 0:14
5

hook_page_build() has been deprecated in favor of hook_page_attachments() as documented on Added hook_page_attachments(_alter)() and removed hook_page_build/alter().

For example, to attach a library to every page, the hook implementation would be similar to the following one.

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.