原则实体中的验证注释

时间:2019-06-28 13:47:27

标签: symfony validation entities

嗨,我有一个symfony项目,其中有一个名为CompanyController的控制器。 我具有根据通过POST方法发送的某些数据保存新公司的功能。

下面,我显示此方法:

/**
     * @param Request $request
     * @param ValidatorInterface $validator
     * @return string|Response
     */
    public function store(Request $request, ValidatorInterface $validator) {
                $company = new Company();
                $company->setName($request->get('name'));
                $company->setTaxNumber($request->get('taxNumber'));
                $company->setStreet($request->get('street'));
                $company->setCity($request->get('postalCode'));
                $company->setOfficeId($request->get('officeId'));
                $company->setPostalCode($request->get('postalCode'));
                $errors = $validator->validate($company);
                if(count($errors) > 0) {
                    /**
                     * some code
                     */
                }
        /**
         * some response
         */
    }

在这种方法中,我尝试验证POST响应中的数据。我想知道在实体文件公司中放置注解进行验证是否是一个好习惯,如下所示:

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="App\Repository\CompanyRepository")
 */
class Company
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     * @Assert\NotBlank
     */
    private $name;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank
     */
    private $taxNumber;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     * @Assert\NotBlank
     */
    private $street;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank
     */
    private $city;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank
     */
    private $postalCode;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank
     *
     */
    private $officeId;

    /**
     * @var datetime $created
     *
     * @ORM\Column(type="datetime")
     */
    protected $createdAt;

    /**
     * @var datetime $updated
     *
     * @ORM\Column(type="datetime", nullable = true)
     */
    protected $updatedAt;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Employee", mappedBy="company")
     */
    private $employees;

    public function __construct()
    {
        $this->employees = new ArrayCollection();
    }


    /**
     * Gets triggered only on insert
     * @ORM\PrePersist
     */
    public function onPrePersist()
    {
        $this->createdAt = new \DateTime("now");
    }

    /**
     * Gets triggered every time on update
     * @ORM\PreUpdate
     */
    public function onPreUpdate()
    {
        $this->updatedAt = new \DateTime("now");
    }


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

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(?string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getTaxNumber(): ?string
    {
        return $this->taxNumber;
    }

    public function setTaxNumber(string $taxNumber): self
    {
        $this->taxNumber = $taxNumber;

        return $this;
    }

    public function getStreet(): ?string
    {
        return $this->street;
    }

    public function setStreet(?string $street): self
    {
        $this->street = $street;

        return $this;
    }

    public function getCity(): ?string
    {
        return $this->city;
    }

    public function setCity(string $city): self
    {
        $this->city = $city;

        return $this;
    }

    public function getPostalCode(): ?string
    {
        return $this->postalCode;
    }

    public function setPostalCode(string $postalCode): self
    {
        $this->postalCode = $postalCode;

        return $this;
    }

    public function getOfficeId(): ?string
    {
        return $this->officeId;
    }

    public function setOfficeId(string $officeId): self
    {
        $this->officeId = $officeId;

        return $this;
    }

    /**
     * @return Collection|Employee[]
     */
    public function getEmployees(): Collection
    {
        return $this->employees;
    }

    public function addEmployee(Employee $employee): self
    {
        if (!$this->employees->contains($employee)) {
            $this->employees[] = $employee;
            $employee->setCompany($this);
        }

        return $this;
    }

    public function removeEmployee(Employee $employee): self
    {
        if ($this->employees->contains($employee)) {
            $this->employees->removeElement($employee);
            // set the owning side to null (unless already changed)
            if ($employee->getCompany() === $this) {
                $employee->setCompany(null);
            }
        }

        return $this;
    }
}

这是正确的方法吗?我遇到的第二种方法是将注释放入完全不同的Entity文件中。例如:

public function productPostAction(AccessChecker $checker, Request $request, JsonFromDbObjectConverter $converter){
        $productRequest = new ProductRequest();
                $productRequest->name = $request->get('name');
                $productRequest->users = $request->get('users');
                $productRequest->llc = (int)$request->get('llc');

                $validator = $this->get('validator');
                $errors = $validator->validate($productRequest);

                if (count($errors) > 0) {
                        /**
                        * some code
                        */

                }
                /**
                * some response
                */
}

用于验证的单独实体类:

<?php

namespace CblBundle\Request;

use Symfony\Component\Validator\Constraints as Assert;

class ProductRequest
{
    /**
     * @var string
     *
     * @Assert\NotBlank()
     */
    public $name;

    /**
     * @var array
     */
    public $users;

    /**
     * @var int
     * @Assert\Type("integer")
     */
    public $llc;

    /**
     * @Assert\IsTrue(message = "Wrong users data!")
     */
    public function isUsersTypeOfNullOrArray()
    {
        return (is_null($this->users) || is_array($this->users));
    }
}

1 个答案:

答案 0 :(得分:1)

实体对输入验证一无所知。这不是他们的工作。我个人从不这样做。还有其他选项-如果使用前两个,则取决于FormType。

  1. Defining form validation constraints in formtypes in symfony-可以,但是如果您退出FormType类,则验证规则也会执行,因此它是高度耦合的方法。不建议这样做!
  2. Defining form validation annotations in models in symfony-可以,因为现在有一个验证专用的独立模型类。 Entity和FormType都不知道验证。只有验证模型知道它,因此所有这些模型都相互分离。即使删除FormType,您仍然可以将验证模型类与Symfony Serializer和Validator一起使用。下面的例子做到了。
  3. Validating, serialising and mapping json request to model classes-这是最终的首选方法。如上所述,无论您是否使用FormTypes,我都将使用此选项。如果愿意,可以使用本机Symfony序列化器而不是JMS。同一博客中还有更多示例。