Jump to the navigation menu

Revisiting the Null Object pattern in Drupal

The Null Object pattern is one of my favourite ways to DRY up code and reduce duplication.

I wrote the System User module for a client project a number of years ago, which also included the Null User module.

If no system user is found, it returns a null (empty) user instead that returns null or empty values by default.

Today, I posted and tooted a screenshot of some code from a side project I'm working on, which I realised would be another good time to use the Null User module.

In the code, I search for a user with a given licence key.

If a user is found, it is returned.

If not, instead of returning FALSE or NULL, I return a null user object that I can treat the same as a real user.

Now, when I create the node and assign an owner, I can just use $account->id() and it will always work if a user was found or not.

This makes the code cleaner, simpler and easier to test and maintain.

- Oliver

Was this interesting?

Sign up here and get more like this delivered straight to your inbox every day.

About me

Picture of Oliver

I'm an certified Drupal Triple Expert with 18 years of experience, a Drupal core contributor, public speaker, live streamer, and host of the Beyond Blocks podcast.