oliverdavies.uk/source/_daily_emails/2024-08-30.md

1.5 KiB

title date permalink tags cta snippet drupal_planet
Revisiting the Null Object pattern in Drupal 2024-08-30 daily/2024/08/30/revisiting-the-null-object-pattern-in-drupal
software-development
drupal
drupal-module
open-source
php
design-patterns
~ Whilst working on my secret side project, today I decided to revisit the Null User Drupal module. true

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.