When to use a trait?

Posted on by Matthias Noback

When to use a trait? Never.

Well, a trait could be considered to have a few benefits:

Decoupling your security user from your user model

Posted on by Matthias Noback

This article shows an example of framework decoupling. You'll find a more elaborate discussion in my latest book, Recipes for Decoupling.

Why would it be nice to decouple your user model from the framework's security user or authentication model?

Effective immutability with PHPStan

Posted on by Matthias Noback

This article is about a topic that didn't make the cut for my latest book, Recipes for Decoupling. It still contains some useful ideas I think, so here it is anyway!

DateTimeImmutable is mutable

I don't know where I first heard it, but PHP's DateTimeImmutable is not immutable:

<?php

$dt = new DateTimeImmutable('now');
echo $dt->getTimestamp() . "\n";

$dt->__construct('tomorrow');
echo $dt->getTimestamp() . "\n";

The result:

1656927919
1656972000

Indeed, DateTimeImmutable is not really immutable because its internal state can be modified after instantiation. After calling __construct() again, any existing object reference will have the modified state as well. But an even bigger surprise might be that if a constructor is public, it's just another method that you can call. You're not supposed to, but you can. Which is another reason to make the constructor of non-service objects private and add a public static constructor to a class that you want to be immutable: