Why Drupal module developers should be excited about object-oriented hooks

Published October 29, 2024

It's not super-often that a Drupal core change record stops me in my tracks, but recently, one did exactly that.

With so much of Drupal core written using modern, object-oriented PHP, there was still one place where we needed to use plain-old PHP functions: hook implementations. Drupal hooks have been with us since before I started with Drupal (over 18 years ago,) and I had long hoped that with the advent of "modern" Drupal (Drupal 8+,) eventually hooks would be converted over to Symfony events

Much to my surprise, a recent change record for Drupal 11.x-dev (to be included in Drupal 11.1) has virtually all hooks (there are some exceptions) now being available as "object oriented hook implementations." 😀

The change record that put that smile on my face:
 

Screenshot of change record that introduces OO hooks to Drupal core 11.1

Support for object oriented hook implementations using autowired services

The short version

Classes can now be written that include methods that can act as hook implementation via a PHP attribute.

Click on the change record link above for a code sample. 

Just as cool - there's backward compatibility built-in so that you can start writing OO hooks today

The longer version

Go read the entire change record. 👍🏼

Why is this such a good thing?

  • First, less plain-old PHP functions + more classes = more modern PHP.
  • Secondly, these hook classes are services, which makes them more performant than plain-old PHP functions.
  • Thirdly, you can organize related hooks in their own classes.

Where can I see this in action?

Together with students from our current Professional Module Development class, we put together a quick module that:

  1. Implements hook_user_login() using this new technique to display a welcome message to the user. 
  2. Includes the backwards compatibility stuff so that it works in Drupal 10.3+
  3. Is written with both Drupal coding standards and PHPStan level 6 compliance. 

Feel free to download or clone the no_more_hooks module from GitHub and check it out on your Drupal 10.3 or 11 site!

Comments

Fourthly, you can implement multiple instances of hooks with different function names. This keeps branching logic out of your hook implementations.

Submitted by Ryan Price (not verified) on Wed, 10/30/2024 - 14:56

Where can I see this in action?

soon, everywhere, nicxvan converted all hooks in core, hopefully it'll be committed in the beta window nov 11-25

Submitted by Guest (not verified) on Fri, 11/01/2024 - 05:31

Add new comment

Sign up to receive email notifications of whenever we publish a new blog post or quicktip!

Name