Multi-purpose Value Objects for Laravel


November 1st, 2022

Multi-purpose Value Objects for Laravel

Laravel Value Objects is a collection of general-purpose value objects you can use in your Laravel application. Value objects help represent simple entities such as money or X/Y coordinates on a 2D axis. Specifically, this package offers the following value objects you'd typically run into:

  • Boolean
  • Number
  • Text
  • Email
  • Full Name
  • Name
  • Tax Number
  • UUID

Take working with a user's full name, for example you might need to split up a name string into a first and last name:

1$name = new FullName(' Joe User ');
3$name->fullName(); // 'Joe User'
4$name->firstName(); // 'Joe'
5$name->lastName(); // 'User'

This package also provides some Laravel-specific goodies, such as extending value objects via Laravel's Macroable trait and Laravel's Conditionable trait, which applies a callback when a condition is "truthy":

2 ->when(function ($number) {
3 return $number->prefix() !== null;
4 })
5 ->prefix();

Another example is the Number value object, which you can use to scale numbers for example:

1$number = new Number('10.20999', scale: 2);
2$number = Number::make('10.20999', scale: 2);
3$number = Number::from('10.20999', scale: 2);
5$number->value(); // '10.20'
6(string) $number; // '10.20'
7$number->toArray(); // ['10.20']

As you can also see, this package provides a few static constructors you can use to create a value object and handle invalid data via the makeOrNull() static constructor.

You can learn more about this package, get full installation instructions, and view the source code on GitHub. The readme has documentation on how to use each of the provided value objects.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.