PHP has introduced a number of new features that allow you to write awesome Value Objects with PHP 8.1. In this post you will learn about each feature and how to put them all together.
Back in the dark ages of 2016, shortly after PHP 7.0 was released, I wrote a Missing In PHP 7 blog post series. Four of the five posts describe functionality that is no longer missing, as of PHP 8.1 or earlier. Missing in PHP7: Value objects is one of those posts.
You can find a quick recap on what a Value Object is, and why you would want to use them, in Missing in PHP7: Value objects.
New features/syntax since PHP 7.0
- PHP 7.4 brought us Typed Properties
- PHP 8.0 brought us Named Arguments and Constructor Property Promotion
- PHP 8.1 brought us Readonly Properties (and New in Initializers)
Value Object using PHP 8.1 features
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class ContactRequest { public function __construct( public readonly string $firstName = 'nyan', public readonly string $lastName = 'cat', public readonly string $emailAddress = 'something', ) { } } $request = new ContactRequest(firstName: 'foo', lastName: 'bar', emailAddress: 'baz'); $firstName = $request->firstName; $request->lastName = 'hax'; // Fails |
Bonus
Other new PHP features that I am excited about:
- Pure Intersection Types (PHP 8.1)
- First-class Callable Syntax (PHP 8.1)
- Mixed return type and Union types (PHP 8.0), typically just for legacy code though