Since PHP 8.4, it is possible to hydrate objects lazily. The hydrator then returns a lazy proxy and the actual hydration happens only when the object is accessed for the first time. This saves work when you hydrate many objects but only touch a few of them.
You can define for each class whether you want it to be lazy by using the
Lazy attribute.
use Patchlevel\Hydrator\Attribute\Lazy;
#[Lazy]
final readonly class ProfileCreated
{
public function __construct(
public string $id,
public string $name,
) {
}
}If you are using a PHP version older than 8.4, the attribute is ignored and the object is hydrated eagerly.
Instead of marking every class, you can make lazy hydration the default when building the hydrator.
use Patchlevel\Hydrator\CoreExtension;
use Patchlevel\Hydrator\StackHydratorBuilder;
$hydrator = (new StackHydratorBuilder())
->useExtension(new CoreExtension())
->enableDefaultLazy()
->build();Single classes can then opt out again with the attribute:
use Patchlevel\Hydrator\Attribute\Lazy;
#[Lazy(false)]
final readonly class ProfileCreated
{
public function __construct(
public string $id,
public string $name,
) {
}
}Cryptography is very expensive in terms of performance. You can combine it with lazy objects so the data is only decrypted when you actually access the object.