Daily Archives: 6th of March 2022

Attributes are awesome

Especially in combination with constructor property promotion.

Recently I did a code-review on an entity from a PHP8.0 project. What I saw was this:

The origin

<?php

declare(strict_types=1);

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
#[ORM\Table(name: 'user')]
class User
{
    #[ORM\Id]
    #[ORM\Column(type: 'integer', unique: true)]
    public int $id;

    #[ORM\Column(type: 'string')]
    public string $username;

    #[ORM\Column(type: 'string')]
    public string $passwordhash;

    public function __construct(
        int $id,
        string $username,
        string $passwordhash,
    ) {
        $this->id = $id;
        $this->username = $username;
        $this->passwordhash = $passwordhash;
    }
}

I was thinking about using constructor property promotion to get rid of the property declaration and property assignment but immediately thought that that would require us to handle the attributes differently. So I shortly checked my favourite search engine and realized that indeed we are able to shorten this whole stuff considerably:

The result

<?php


declare(strict_types=1);

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
#[ORM\Table(name: 'user')]
class User
{
    public function __construct(
        #[ORM\Id]
        #[ORM\Column(type: 'integer', unique: true)]
        public int $id,
        #[ORM\Column(type: 'string')]
        public string $username,
        #[ORM\Column(type: 'string')]
        public string $passwordhash,
    ) {}
}

Combining the attributes with the constructor property promotion allows much smaller entity definitions.

Immutability

In our case we also cleared a misunderstanding. My colleague was under the impression that Doctrine requires properties to be public. Otherwise they are not able to be hydrated properly. That is not the case and Doctrine can perfectly hydrate private properties!

So we decided to go for private properties in combination with getters. As in our concrete implementation we actually also need to execute some logic before returning some of the values. So declaring the properties private and having getters provides us with a truly immutable entity.

As we are not using PHP8.1 yet we could not make use of the new readonly declaration which would have solved the issue with the immutability though as we need logic in some cases the approach with using getters always makes more sense in this particular setup.