Symfony: release form using return type in Entity methods

Today I was very diligent and decided to return a type that hints at all of my symfony entity methods. So:

<?php

Class User {
    private string $username;
    public method getUsername(): string {}
}

      

all is well and good until I create a form to create a new user:

$user = new User();
$this->createForm(SignupType::class, $user);

      

when the form is rendered, Symfony automatically gets the properties of this new instance User $user

. But since this is a new instance, its property username

is of course still null

, which is the wrong return type as it should be string

.

Should I:

  • do not have a return type in Symfony objects (meh);
  • set $username = ''

    (but the hat kind of defeats the goal of not allowing spaces and I can see all sorts of bugs developing); or
  • Cancel a field in symfony form
  • other possible solutions ...
+3


source to share


2 answers


If the Entity property cannot be null

(and you are using PHP 7.1+), then applying a nullable return type is more like a dirty and quick workaround for maintaining direct data binding between objects and forms (using the Symfony form component).

The best global approach (in my opinion) is to decouple the form data binding from your Entities using a DTO (Data Transfert Object), which is a simple POPO (Plain Old PHP Object), to contain your form data.

Using DTOs will allow you to maintain strong hint types in your entities (without losing data consistency) and will decouple form data binding (but also data validation) from your objects.



DTO is reusable and has many other benefits.

Some helpful references on using DTOs with Symfony Forms:

+9


source


If you are using PHP 7.0, which does not have support for declaring a null return type, the first option will be correct (non-hacky). If you are using PHP 7.1+ you can define a nullable return type declaration .



<?php

class User 
{
    public function getUsername(): ?string {}
}

      

+2


source







All Articles