Add daily email for 2024-08-30

Revisiting the Null Object pattern in Drupal
This commit is contained in:
Oliver Davies 2024-08-29 23:59:05 +01:00
parent e90a5a6630
commit 8e2060dea6

View file

@ -0,0 +1,38 @@
---
title: Revisiting the Null Object pattern in Drupal
date: 2024-08-30
permalink: daily/2024/08/30/revisiting-the-null-object-pattern-in-drupal
tags:
- software-development
- drupal
- drupal-module
- open-source
- php
- design-patterns
cta: ~
snippet: |
Whilst working on my secret side project, today I decided to revisit the Null User Drupal module.
---
The Null Object pattern is one of my favourite ways to DRY up code and reduce duplication.
I wrote the [System User module][0] for a client project a number of years ago, which also included the [Null User module][1].
If no system user is found, it returns a null (empty) user instead that returns null or empty values by default.
Today, [I posted][2] [and tooted][3] 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.
[0]: https://www.drupal.org/project/system_user
[1]: https://www.drupal.org/project/null_user
[2]: https://x.com/opdavies/status/1829183673725284772
[3]: https://mastodon.social/@opdavies/113046773292848198