Skip to content

Instantly share code, notes, and snippets.

@glennpratt
Created March 9, 2012 23:35
Show Gist options
  • Select an option

  • Save glennpratt/2009300 to your computer and use it in GitHub Desktop.

Select an option

Save glennpratt/2009300 to your computer and use it in GitHub Desktop.

Use namespaced, static methods for hooks instead of functions.

<?php
example_boot();
// Becomes
Drupal\Module\Example\Hook\System::boot();

example_menu();
// Becomes
Drupal\Module\Example\Hook\Menu::register();

example_user_delete()
// Becomes
Drupal\Module\Example\Hook\User::delete();

example_install()
// Becomes
Drupal\Module\Example\Hook\Schema::install();

example_update_8001()
// Becomes
Drupal\Module\Example\Hook\Schema::update8001();

Motivation

  • Reduce pollution of the global namespace.
  • Hook implementations can be autoloaded (reduce bootstrap code footprint).
  • Hook implementations are grouped by functionality.
  • Hook implementations can be seperated from .module file, leaving it only for global API functions a module would like to expose or completely gone - http://drupal.org/node/340723.
  • Hook implementations are more visible/discoverable by both humans and machines.
  • Implementations can be included by usage, not required at mode change (e.g. bootstrap level, .install).

Assumptions

  • Core autoloader will support contrib.
    • And the namespace will be Drupal\Module\{ModuleName}... that's an easy one to change.

Q/A

This introduces new magic directories/files!

Not entirely true. As long as you can provide the classes before module_invoke (which would continue to load the .module file if present), they don't have to be included by the autoloader. Example putting the namespace'd code inside example.module:

<?php
/**
 * @file
 * example.module
 * This example leaves hooks in the .module file.
 */

namespace Drupal\Module\Example\Hook {
  class Menu {
    public static function register() {
      // snip
      return $items;
    }
    public static function alter(&items) {
      // snip
    }
  }

  class System {
    public static function boot() {
      // Whatever
    }
  }
}

// Normal, global namespace code.
namespace {
  /**
   * Blah, blah, blah.
   */
  function example_stuff() {
    return NULL;
  }
}
 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment