Should non-nullable entity properties be nullable type in PHP?

Viewed 47

Using Symfony 6.1, I have this Entity:

#[ORM\Entity(repositoryClass: InvoiceRepository::class)]
class Invoice implements SearchableEntityInterface
{

    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private int $id;

    #[ORM\Column(type: 'datetime')]
    private DateTimeInterface $timeCreated;

    #[ORM\Column(type: 'datetime', nullable: true)]
    private ?DateTimeInterface $timePaid = null;

    // ...
}

The only nullable field in DB is timePaid, the rest is required to be NOT NULL in DB.

My code reflects "nullability" of DB in PHP code, i.e. if the field can be NULL in DB, then its nullable in PHP, but never otherwise.

However when using the make:entity or checking online examples you always see

    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private ?int $id;

    #[ORM\Column(type: 'datetime')]
    private ?DateTimeInterface $timeCreated;

i.e. nullable PHP properties even when it CANNOT be null ever.

Is it correct to declare ID field and non-nullable fields as non-nullable in PHP? Can there be any issues from this approach?

0 Answers
Related