Symfony 4 API Rest PUT:将数据映射到数据库实体 [英] Symfony 4 API Rest PUT : Map data to database entity

查看:66
本文介绍了Symfony 4 API Rest PUT:将数据映射到数据库实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Symfony 4的入门者,正在开发API Rest.我想创建一个可以处理许多更新案例的PUT资源.

I'm a begginer in Symfony 4 and I'm developing an API Rest. I want to create a PUT resource that can handle many update cases.

在我的情况下,我有一个具有许多属性的用户,但我将举一个具有3个属性的示例来使事情保持简单:

In my case, I have a user with many properties but I will take an example with 3 properties to keep things simple :

User {
    username,
    email,
    password
}

可以调用我的PUT资源以更新用户名,更新电子邮件或更新密码.例如,要更新用户名,我API的用户将发送仅包含用户名的PUT请求:

My PUT resource can be called in order to update Username, update Email or update Password. For example, to update Username, the user of my API will send a PUT request with only username :

{
    username: "New username"
}

与电子邮件和密码相同,他只会发送要更改的属性.

Same for email and password, he will only send the property he wants to change.

我的问题出在控制器上,我必须做这样的事情:

My problem is in my Controller, I have to do things like this :

/**
 * @Rest\Put("/user/{id}")
 * @param Request $request
 * @return View
 */
public function putUserRequest(Request $request)
{
    $userId = $request->get('id');
    $user = $this->doctrine->getRepository(User::class)->findOneBy('id' => $userId);

    $userFromRequest = $this->serializer->deserialize($request->getContent(), User::class, 'json'); 

    if ($userFromRequest->getUsername() != NULL) {
        $user->setUsername($userFromRequest->getUsername())
    }
    if ($userFromRequest->getEmail() != NULL) {
        $user->setEmail($userFromRequest->getEmail())
    }
    if ($userFromRequest->getPassword() != NULL) {
        $user->setPassword($userFromRequest->getPassword())
    }
    // ...
}

在我的示例中,我只有3个属性,但是想象一下,当我有30个属性时.

In my example I have only 3 properties, but imagine when I have 30 properties.

在Symfony 3中,我使用表格来验证/保存数据:

With Symfony 3 I used forms to validate / save my datas :

$form->submit($request->request->all(), $clearMissing);

如果$ clearMissing为false,则会保留我的API用户未提供的数据.我找不到使用序列化程序执行此操作的方法,但我想我做错了事.

Where $clearMissing is false to keep datas not provided by the user of my API. I can't find a way to do it with serializer but I guess I'm doing things wrong.

谢谢.

推荐答案

如果我理解正确,则可以使用验证器组件,如下所示:

If I understand correctly, You can use the validator Component like this :

/**
 * @Rest\Put("/user/{id}")
 * @param Request $request
 * @return View 
 */
public function putUserRequest(User $user, Request $request, ValidatorInterface $validator)
{

 $data = $request->getContent();

 $this->serializer->deserialize($data, User::class, 'json', ['object_to_populate' => $user]); 

//At this moment, the data you sent is merged with your user entity 

 /** @var ConstraintViolationList $errors */
  $errors = $validator->validate($user, null ,['groups' => 'user_update']);

   if (count($errors) > 0) {
       //return json reponse with formated errors;
   }

   //if ok $entityManager->flush() and Response Json with serialization group;

    ...

}

在您的用户类别中:

class User implements UserInterface
{
    /**
     * @Assert\Email(groups={"user_create", "user_update"})
     */
    private $email;

    /**
     * @Assert\NotBlank(groups={"user_create", "user_update"})
     * @Assert\Length(min=7, groups={"user_create", "user_update"})
     */
    private $password;

    /**
     * @Assert\Length(min=2, groups={"user_create", "user_update"} )
     */
    private $username;
}

相关的Validator组件文档: https://symfony.com/doc/current/validation/groups.html

Related Validator component documentation : https://symfony.com/doc/current/validation/groups.html

您还可以检查以下项目: https://github.com/attineos/relation-deserializer

You can also check this project : https://github.com/attineos/relation-deserializer

这篇关于Symfony 4 API Rest PUT:将数据映射到数据库实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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