A baseline file, a few generics, and a plan to pay down the rest. PHP has quietly become a pleasant language to write. Typed properties, enums, readonly classes, and now property hooks remove a lot of the boilerplate that gave it a bad reputation.
Modern PHP, minus the ceremony
We took a class from a six-year-old codebase and rewrote it with current language features. The result is half the length and, more importantly, the invalid states are no longer representable.
<?php
final readonly class Money
{
public function __construct(
public int $amount,
public Currency $currency,
) {
if ($amount < 0) {
throw new InvalidArgumentException('Amount cannot be negative.');
}
}
public function add(Money $other): self
{
return new self($this->amount + $other->amount, $this->currency);
}
}
Refactoring the old version
Static analysis turns those types into guarantees. Start at a low level with a baseline file, raise the level one step per sprint, and never let the baseline grow.
- Use readonly properties for value objects.
- Replace string constants with backed enums.
- Commit a PHPStan baseline and shrink it over time.
- Autoload everything through Composer.
Static analysis catches the rest
None of this requires a framework. The examples run on plain PHP 8.3 or newer with Composer’s autoloader, and they translate directly to Laravel or Symfony projects.
We have been running this approach for several months now. The initial setup took about a day, and the ongoing cost is close to zero once the team knows where to look.
Before you ship this
Readonly classes cannot be cloned with changed values before PHP 8.3. Check your minimum version before adopting them in a shared library.
Program testing can be used to show the presence of bugs, but never to show their absence!
Edsger W. Dijkstra, Notes on Structured Programming, 1970
Wrapping up
Questions, corrections, and war stories are welcome in the comments. Several of our best follow-up posts started as a reader pointing out something we had missed.
Thanks for including the numbers. So many posts skip the measurement part.
+1, this matches what we saw after the migration.
The renaming spree is a rite of passage.
Agreed. Start simple and only reach for this when you feel the pain.
Agreed. Start simple and only reach for this when you feel the pain.
Is there a repo with the full example? Happy to open a PR with a TypeScript version.
A repo is on the way. I will link it in the post once it is cleaned up.
Counterpoint: for small teams the simpler approach in the first section is usually enough.
Any thoughts on how this interacts with server-side rendering?
Is there a repo with the full example? Happy to open a PR with a TypeScript version.
Great post. Did you measure the impact before and after, or is this mostly from experience?