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.

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

6

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();   
  ...
}
  • How to use ['#attached]['js] in function initializeMyModule? SInce there is no $var, $page or somether argument in the function. – neha Aug 9 '16 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 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 (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.

  • 4
    You should never use drupal_add_js / drupal_add_css -- even in Drupal 7 they are better avoided -- better use #attached. I removed this part. – user49 Sep 10 '13 at 8:12
  • 1
    @chx, drupal_process_attached also uses drupal_add_css/js to add the page requisites in call_user_func('drupal_add_' . $type, $data, $options); – David Thomas Sep 10 '13 at 8:54
  • 1
    Yes but drupal_process_attached fires after the render cache is retrieved. If you do #attached then your CSS/JS will be added even when the render cache is used. – user49 Jan 25 '14 at 19:22
  • 2
    Appears that hook_page_build isn't a thing in D8 anymore? – digitgopher Jan 22 '16 at 0:14
4

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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