Mastering Object-Oriented Hooks in Drupal 11: How to Use Hook Service Classes Effectively
Drupal 11.1.0 introduces a major shift in its extensibility model with the rollout of object-oriented (OOP) service hooks, replacing the long-standing procedural hook system. Phil Norton of Hashbang Code outlines this transition, emphasizing improved testability, modularity, and developer experience.
The new system lets developers register hooks as PHP attributes in service classes, enabling automatic dependency injection and unit testing. Norton walks through defining hooks via class or method attributes, stacking hooks, and leveraging the #[LegacyHook] attribute for backward compatibility. Developers can now explicitly test hooks using PHPUnit, avoiding complex setups previously required for procedural functions.
While all major hooks are expected to adopt this OOP approach, Norton notes some exceptions may persist for install/update routines. He urges module maintainers to adopt OOP hooks early while maintaining legacy compatibility where necessary. The article concludes with a full example of defining and using a custom hook in the new system.


