Your Location is: Home > Doctrine-orm

Zend framework 3 form issue with binding entities that use return type hinting

From: Yaren View: 4484 Systemfreak 

Question

As I'm upgrading my application to PHP 7.3, I decided to add return type hinting to my entities methods. An example would be something like this:

class User {
    private $username;
    public method getUsername(): string { return $this->username}
}

I use this entity in a form (to create users) where I bind it like so:

$user = new User();
$form->bind($user);
$form->setData($data);

However I get this error which is caused by the hydrator (I'm using the DoctrineObject hydrator)

Return value of Admin\Entity\Auth\User::getUsername() must be of the type string, null returned
#0 ...\vendor\doctrine\doctrine-module\src\DoctrineModule\Stdlib\Hydrator\DoctrineObject.php(220): Admin\Entity\Auth\User->getUsername()
#1 ...\vendor\doctrine\doctrine-module\src\DoctrineModule\Stdlib\Hydrator\DoctrineObject.php(116): DoctrineModule\Stdlib\Hydrator\DoctrineObject->extractByValue(Object(Admin\Entity\Auth\User))
#2 ...\vendor\zendframework\zend-form\src\Fieldset.php(650): DoctrineModule\Stdlib\Hydrator\DoctrineObject->extract(Object(Admin\Entity\Auth\User))
...

From the snippet above it's obvious that it's calling the getUsername method on an "empty" object, which makes it return null and throw the exception.
This is not logically correct as the entity is supposed to have a username so marking it as nullable (?string) is not correct.

Is there any better solution to this? Because making every single method return type nullable seems like a hack that defeats the purpose.

Best answer