gpt4 book ai didi

php - 使用 Symfony Validator 验证 Doctrine 实体

转载 作者:行者123 更新时间:2023-12-01 22:33:02 25 4
gpt4 key购买 nike

我很难将 Symfony 验证器组件与 Doctrine 集成(独立的,不使用完整的 Symfony 框架)。到目前为止,我已经成功地在 Doctrine 的 AnnotationRegistry 中注册了注释约束并 Hook 到生命周期回调中,但是我如何实际检索验证器并解析生命周期方法中的注释?

我的实体看起来像这样:

<?php
namespace App\Model;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
* User
*
* @ORM\HasLifecycleCallbacks
* @ORM\Table(name="users", uniqueConstraints={@ORM\UniqueConstraint(name="id_UNIQUE", columns={"id"}), @ORM\UniqueConstraint(name="username_UNIQUE", columns={"username"})})
* @ORM\Entity(repositoryClass="App\Repository\UserRepository")
*/
class User extends AbstractEntity
{
/**
* @ORM\PreUpdate
* @ORM\PrePersist
*/
public function validate()
{
// how do I retrieve the validator?

// $validator->validate($this);
}

/**
* @var string
*
* @ORM\Column(name="username", type="string", length=45, nullable=false)
* @Assert\Length(min=3, max=45)
*/
protected $username;

/** ... */
}

最佳答案

因为你没有使用 symfony fullstack,你应该手动创建一个验证器服务来使用它。

参见 Usage Section of Validator component readme

use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints as Assert;

class User
{
/**
* @Assert\Length(min = 3)
* @Assert\NotBlank
*/
private $name;

/**
* @Assert\Email
* @Assert\NotBlank
*/
private $email;

public function __construct($name, $email)
{
$this->name = $name;
$this->email = $email;
}

/**
* @Assert\True(message = "The user should have a Google Mail account")
*/
public function isGmailUser()
{
return false !== strpos($this->email, '@gmail.com');
}
}

验证器

$validator = Validation::createValidatorBuilder()
->enableAnnotationMapping()
->getValidator();

$user = new User('John Doe', 'john@example.com');

$violations = $validator->validate($user);

关于php - 使用 Symfony Validator 验证 Doctrine 实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28641360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com