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

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

问题描述

我今天特别勤奋,决定返回类型提示我所有的 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. set $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+),则应用可空返回类型声明 听起来更像是一种肮脏而快速的解决方法来维护实体和表单之间的直接数据绑定(使用 Symfony 表单组件).

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(数据传输对象)将表单数据绑定与您的 Doctrine 实体分离,这是一个简单的POPO(Plain Old PHP Object)包含您的表单数据.

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 Forms 中使用 DTO 的有用参考:

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

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

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