I would like know if it's possible to use hook inside a class and inside .module file.

By example :


use Drupal\xenforo\Xenforo\XenAPI;
use Drupal\Core\Entity\EntityInterface;
Class XenforoBridgeIntegration {
    // use Drupal 8 hook here and can use OrientedObject inside

I have try, but hook don't work if it's inside a class ?


1 Answer 1


No, it's not possible.

Hooks are functions that exist in the global namespace. Class/instance methods cannot be used to implement them.

If you take a look at the very simple ModuleHandler::invoke method, you'll see this in action:

public function invoke($module, $hook, array $args = array()) {
  if (!$this->implementsHook($module, $hook)) {
  $function = $module . '_' . $hook;
  return call_user_func_array($function, $args);

As you can see, you must have a function called MODULENAME_HOOKNAME available in the global namespace, no consideration is given to classes or namespace resolution.

You can (and probably should) hand off whatever processing you're doing inside the hook to a specific class, but the hook itself will need to be implemented in procedural style.

  • 1
    If you want to keep your code in classes, you could implement a slim function that calls a service or static method. Payment does that for example, but I personally find that goes too far :)
    – Berdir
    Jan 20, 2015 at 20:26

Your Answer

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

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