Symfony:在Doctrine Entity方法中使用Return类型提示的表单问题 [英] Symfony: Form issue using Return type hinting in Doctrine Entity methods

查看:73
本文介绍了Symfony:在Doctrine Entity方法中使用Return类型提示的表单问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天非常勤奋,决定返回类型提示所有我的symfony实体方法.所以:

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);

显示表单时,Symfony自动获取此User $user的新实例的属性.但是,由于它是一个新的实例,因此它的username属性当然仍然是null,这是一个错误的返回类型,因为它必须为string.

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.

我应该:

  1. 在Symfony实体中没有返回类型提示(meh);
  2. 设置$username = ''(但是,这有点违反了不允许空白的目的,我可以看到各种错误在演变);或
  3. 在symfony表单上取消映射字段
  4. 其他可能的解决方案...
  1. have no return-type hinting in Symfony entities (meh);
  2. set $username = '' (but hat kind of defeats the purpose of not allowing blanks and I can see all sorts of errors evolving); or
  3. unmap the field on the symfony form
  4. other possible solutions...

推荐答案

如果实体属性不能为null(并且您使用PHP 7.1 + ),则应用

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).

一种更好的全局方法(在我看来是 )是使用DTO(数据传输对象)将表单数据绑定与您的学说实体分离,这很简单POPO(普通的旧PHP对象)以包含您的表单数据.

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.

使用DTO可以使您在Doctrine实体中维护严格的类型提示(不会丢失数据一致性),并且可以将表单数据绑定(但还可以验证数据))来自您的实体.

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具有可重用性,并具有许多其他优点.

DTO's allows reusability and have many other advantages.

关于在Symfony表单中使用DTO的一些有用参考:

Some useful references about the use of DTO's with Symfony Forms:

  • Avoiding Entities in Forms (by Iltar van der Berg)
  • Rethinking Form Development (by Iltar van der Berg)
  • Symfony Forms 101 (by Bernhard Schussek the creator of the Form component)
  • Don't Use Entities in Symfony Forms. Use Custom Data Objects Instead
  • Entities should always be valid

这篇关于Symfony:在Doctrine Entity方法中使用Return类型提示的表单问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆