The new OOP hook attributes in Drupal 11.2 represent a major evolution in how hooks work. Here's a comprehensive breakdown:
Key Attributes Overview
#[Hook()] - Basic Implementation
The Hook attribute can be used in any of the following ways: On a method, use the attribute with the hook name; On a class, specify the method name as well as the hook name; On a class with an __invoke method, which is taken to be the hook implementation Hook ordering across OOP, procedural and with extra types i.e replace hook_module_implements_alter [#3485896] | Drupal.org
#[RemoveHook()] - Removing Hooks
The execution of a hooks implemented by other modules can be skipped. This is done by removing the targeted hook, use the RemoveHook attribute Hook ordering across OOP, procedural and with extra types i.e replace hook_module_implements_alter [#3485896] | Drupal.org
#[ReOrderHook()] - Controlling Order
The order in which hooks implemented in other modules are executed can be reordered. The reordering of the targeted hook is done relative to other implementations Hook ordering across OOP, procedural and with extra types i.e replace hook_module_implements_alter [#3485896] | Drupal.org
#[Hook('preprocess')] - Preprocess Support
In Drupal 11.2 (or at least 11.1.8), preprocess hooks are also supported in the new OOP way. However, this can only be used in modules; preprocess hooks in themes remain procedural drupal 11.2.3 | Drupal.org
Revolutionary Benefits
- No .module Files Required: You can now build complete Drupal modules without any
.modulefiles - everything can be organized in classes within thesrc/Hook/namespace. - Advanced Hook Management: The new attributes give you unprecedented control over hook execution:
- Remove hooks from other modules
- Reorder hook execution precisely
- Run hooks first, last, or relative to specific other hooks
- Better Developer Experience:
- Full IDE autocomplete and type checking
- Organized, testable code structure
- Clear separation of concerns
This is a game-changing improvement that makes Drupal development much more modern and maintainable!
- Log in to post comments