【问题标题】:What's the recommended way in Symfony of taking JSON data and populating an entity?Symfony 中获取 JSON 数据并填充实体的推荐方式是什么?
【发布时间】:2018-02-28 17:43:45
【问题描述】:

如果我在请求中接收 JSON 数据(比如 API 类型接口),Symfony 推荐的填充实体的方法是什么。在我看来,选项是:

  • 使用表单组件 - 将解码后的 JSON 作为数组传递给 submit() 方法。
  • 使用序列化程序进行反序列化。

在我看来,使用序列化程序的问题在于您需要手动进行数据转换(和验证,虽然很简单)。

使用表单组件感觉有点 hacky,而且还使用了很多不需要的/不需要的功能。

是否有其他选项(内置于 Symfony 或其他捆绑包/包中)?还是其中一种是推荐的方式?

(我意识到这至少部分是基于意见的问题......)

【问题讨论】:

  • 可能想浏览一下api-platform 的文档。它说明了一种相当极端的 api 方法,它可能适合也可能不适合您的项目。创建者也是 Symfony 核心团队的活跃成员。另一方面,不要只写某种自定义转换器。

标签: symfony doctrine-orm symfony-forms


【解决方案1】:

正如您所提到的 - 这是一个非常固执己见的问题。您一直在考虑的选项是两种常见的处理方式:

  1. 只需使用Form 组件 - 需要创建一个 FormType,会增加一些性能开销(在大多数情况下并不重要)。作为奖励 - 它为您提供所有表单特权,例如不允许额外字段、使用表单事件的能力等。
  2. 使用Serializer + Validator - 就所用组件而言,这是一个“瘦”选项,有点冗长,不附带表单特权

我想说,使用表单一次性处理反序列化和验证确实没有错。

查看下面的示例操作代码。请注意,它使用 FOSRestBundle View 类来处理响应。它只是接收一个 json 编码的实体数据,然后基于它创建一个新实体或更新一个现有实体。

 public function sampleAction(SampleEntity $sampleEntity, Request $request) {

    //Is it a new or existing entity?
    $statusCode = $sampleEntity->getId() ? 200 : 201;

    //Load our form with the entity provided by the route loader
    $form = $this->createForm(SampleEntityType::class, $sampleEntity);

    //Decode the actual input and make Form component to populate an entity for us
    $formData = json_decode($request->getContent(), true);
    $form->submit($formData);

    //Validation is as simple as this
    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($sampleEntity);
        $em->flush();
        return View::create($form, $statusCode);
    }

    return View::create($form->getErrors(true, false), 400);
}

【讨论】:

    猜你喜欢
    • 2021-09-16
    • 1970-01-01
    • 2010-10-19
    • 2011-07-17
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    • 2011-11-05
    • 2012-08-04
    相关资源
    最近更新 更多