Symfony: Form issue using Return type hinting in Doctrine Entity methods Symfony: Form issue using Return type hinting in Doctrine Entity methods php php

Symfony: Form issue using Return type hinting in Doctrine Entity methods


If 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:


If you're using PHP 7.0, which has no nullable return type declaration support, the first option will be the right (non-hacky) choice. In case of you're using PHP 7.1+, you can define a nullable return type declaration.

<?phpclass User {    public function getUsername(): ?string {}}