Data transfer objects and value objects

In the last few emails, we've seen a data transfer object called AccountDetails that stores the account number and sort code for a bank account.

A data transfer object only stores data but we could also use a value object that can do more tasks, like validating the values.

For example, we could validate that the account number is the correct length and the sort code is the correct format:

class AccountDetails {

  public function __construct(
    public readonly string $accountNumber,
    public readonly string $sortCode,
  ) {
    // Validate the account number.
    if (!preg_match('/^\d{8}$/', $accountNumber)) {
      throw new \InvalidArgumentException('Account number must be an 8-digit number');
    }

    // Validate the sort code.
    if (!preg_match('/^\d{2}-\d{2}-\d{2}$/', $sortCode)) {
      throw new \InvalidArgumentException('Sort code must be in the format 00-00-00');
    }
  }

}

Helper methods can also be added to a value object as long as they don't modify the state of the object, such as getting the raw sort code without the separating dashes or performing further checks on the input values.

- 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 Acquia-certified Drupal Triple Expert with 17 years of experience, an open-source software maintainer and Drupal core contributor, public speaker, live streamer, and host of the Beyond Blocks podcast.