POST 方法 api 自定义端点具有不必要的强制 ID 字段

POST method api custom end point having unnecessary mandatory ID field

我有这个自定义 API 端点调用 "register"。我已使用 "POST" 声明添加到用户实体的 "ItemOperations" 中。当我查看 api 平台 UI 时,我看到强制输入不必要的 ID 字段,如所附屏幕截图所示。

这是我尝试过的用户实体代码

<?php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;


/**
 * @ApiResource(
 *     collectionOperations={"get","post"},
 *     itemOperations={
 *     "get",
 *     "put",
 *      "register"={
 *         "method"="POST",
 *         "path"="/register",
 *         "controller"=User::class,
 *     }
 *     },
 *     normalizationContext={
 *                  "groups"={"user:read"},"swagger_definition_name"="Read"
 *      },
 *     denormalizationContext={
 *                  "groups"={"user:write"},"swagger_definition_name"="Write"
 *      },
 *     shortName="User"
 *
 * )
 * @UniqueEntity(fields={"email"})
 * @UniqueEntity(fields={"contact"})
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 */
class User implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=180, unique=true)
     * @Groups({"user:read", "user:write"})
     * @Assert\Email()
     * @Assert\NotBlank()
     */
    private $email;

    /**
     * @ORM\Column(type="json")
     */
    private $roles = [];

    /**
     * @var string The hashed password
     * @ORM\Column(type="string")
     * @Groups({"user:write"})
     * @Assert\NotBlank()
     */
    private $password;

    /**
     * @ORM\Column(type="string", length=255)
     * @Groups({"user:read", "user:write"})
     * @Assert\NotBlank()
     */
    private $firstName;

    /**
     * @ORM\Column(type="string", length=255)
     * @Groups({"user:read", "user:write"})
     * @Assert\NotBlank()
     */
    private $lastName;

    /**
     * @var string provide in YYYY-MM-DD (neglect Time)
     * @ORM\Column(type="date")
     * @Groups({"user:read", "user:write"})
     * @Assert\NotBlank()
     */
    private $dob;

    /**
     * @ORM\Column(type="text")
     * @Groups({"user:read", "user:write"})
     * @Assert\NotBlank()
     */
    private $address;

    /**
     * @ORM\Column(type="string", length=255)
     * @Groups({"user:read", "user:write"})
     * @Assert\NotBlank()
     * @Assert\Length(
     *     min=8,
     *     max=8,
     *     maxMessage="contact number must have 8 character",
     *     minMessage="contact number must have 8 character"
     * )
     */
    private $contact;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }

    /**
     * A visual identifier that represents this user.
     *
     * @see UserInterface
     */
    public function getUsername(): string
    {
        return (string) $this->email;
    }

    /**
     * @see UserInterface
     */
    public function getRoles(): array
    {
        $roles = $this->roles;
        // guarantee every user at least has ROLE_USER
        $roles[] = 'ROLE_USER';

        return array_unique($roles);
    }

    public function setRoles(array $roles): self
    {
        $this->roles = $roles;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getPassword(): string
    {
        return (string) $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getSalt()
    {
        // not needed when using the "bcrypt" algorithm in security.yaml
    }

    /**
     * @see UserInterface
     */
    public function eraseCredentials()
    {
        // If you store any temporary, sensitive data on the user, clear it here
        // $this->plainPassword = null;
    }

    public function getFirstName(): ?string
    {
        return $this->firstName;
    }

    public function setFirstName(string $firstName): self
    {
        $this->firstName = $firstName;

        return $this;
    }

    public function getLastName(): ?string
    {
        return $this->lastName;
    }

    public function setLastName(string $lastName): self
    {
        $this->lastName = $lastName;

        return $this;
    }

    public function getDob(): ?\DateTimeInterface
    {
        return $this->dob;
    }

    public function setDob(\DateTimeInterface $dob): self
    {
        $this->dob = $dob;

        return $this;
    }

    public function getAddress(): ?string
    {
        return $this->address;
    }

    public function setAddress(string $address): self
    {
        $this->address = $address;

        return $this;
    }

    public function getContact(): ?string
    {
        return $this->contact;
    }

    public function setContact(string $contact): self
    {
        $this->contact = $contact;

        return $this;
    }
}

这是我的 AuthController

<?php
    namespace App\Controller;
    use App\Entity\User;
    use Doctrine\ORM\EntityManagerInterface;
    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    use Symfony\Component\Config\Definition\Exception\Exception;
    use Symfony\Component\HttpFoundation\JsonResponse;
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\HttpFoundation\Response;
    use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
    class AuthController extends AbstractController
    {

        /**
         * @param Request $request
         * @param UserPasswordEncoderInterface $encoder
         * @param EntityManagerInterface $entity_manager
         *
         * @return JsonResponse
         * @throws \Exception
         */
        public function register(Request $request, UserPasswordEncoderInterface $encoder, EntityManagerInterface $entity_manager)
        {
            try{
                $contentType = $request->getContentType();
                $content     = $request->getContent();
                $response = new JsonResponse();

                if ($contentType != 'json' || !$content) {
                    $response -> setContent(json_encode(['fail' => 'empty content type or content type is not json format']));
                    $response ->setStatusCode(Response::HTTP_BAD_REQUEST,'Bad Request');
                }else{
                    $data = json_decode($content, true);

                    $email      = $data['email'];
                    $hasUser    = $entity_manager->getRepository(User::class)->findByEmail($email);

                    if($hasUser){
                        $response -> setContent(json_encode(['fail' => 'user already registered']));
                        $response ->setStatusCode(Response::HTTP_BAD_REQUEST,'Bad Request');
                        return $response;
                    }


                    //Update User
                    $user = new User();
                    $user ->setEmail($data['email']);
                    $user ->setFirstName($data['firstName']);
                    $user->setLastName($data['lastName']);
                    $user->setDob(new \DateTime($data['dob']));
                    $user->setAddress($data['address']);
                    $user->setContact($data['contact']);
                    $user->setPassword($encoder->encodePassword($user,
                        $data['password']
                    ));
                    $entity_manager->persist($user);
                    $entity_manager->flush();


                    $response -> setContent(json_encode(['success' => 'user successfully added']));
                    $response -> setStatusCode(Response::HTTP_CREATED,'Created');
                }
                return $response;
            }catch (Exception $e){
                //TODO: Log Error
                $response -> setContent(json_encode(['fail' => 'Internal Server Error']));
                $response ->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR,'Bad Request');
            }
        }

    }

我想在 post 注册时删除 "Id" 必填字段。有什么办法吗?我被这个问题困扰了将近两天。对不起,如果我错过了什么,因为我是 API 平台

的新手

您需要在集合操作中使用 POST 操作,ItemOperation 用于获取、更新或删除您的资源,因此 ID 是必需的。

并将你的动作指向控制器,而不是实体

@ApiResource(
 *     collectionOperations={
 *       "get",
 *       "post",
 *       "register"={
 *         "method"="POST",
 *         "path"="/register",
 *         "controller"= AuthController::class,
 *     }
 *     },
 *     itemOperations={
 *     "get",
 *     "put",
 *     },
 *     normalizationContext={
 *                  "groups"={"user:read"},"swagger_definition_name"="Read"
 *      },
 *     denormalizationContext={
 *                  "groups"={"user:write"},"swagger_definition_name"="Write"
 *      },
 *     shortName="User"
 *  * )