I was being exceptionally diligent today and decided to return-type hint all of my symfony entity methods. So:
<?php
Class User {
private string $username;
public method getUsername(): string {}
}
all good and well, until I made a form to create a new user:
$user = new User();
$this->createForm(SignupType::class, $user);
when the form is displayed, Symfony automatically gets the properties of this new instance of User $user
. But since it is a new instantiation, its username
property is of course still null
, which is an incorrect return type as it needs to be string
.
Should I either:
$username = ''
(but hat kind of defeats the purpose of not allowing blanks and I can see all sorts of errors evolving); orIf an Entity Property cannot be null
(and you use PHP 7.1+), then applying the nullable return type declaration sounds more like a dirty and fast workaround to maintain a direct data binding between Entities and Forms (using the Symfony Form Component).
A better global approach (in my opinion) is to decouple the Form data binding from your Doctrine Entities using a DTO (Data Transfer Object), that is a simple POPO (Plain Old PHP Object) to contain your form data.
Using a DTO will allow you to maintain a strict type hinting in your Doctrine Entities (no loss of data consistency) and will decouple Form data binding (but also data validation) from your Entities.
DTO's allows reusability and have many other advantages.
Some useful references about the use of DTO's with Symfony Forms: