我正在努力通过理论和最佳实践来提高自己。 我发现了一个很好的最佳实践演示:https://ocramius.github.io/doctrine-best-practices/#/50
我尝试在 __construct 之后拥有一个有效的对象。 (参见https://ocramius.github.io/doctrine-best-practices/#/52) 但我使用 @Assert 注释来验证我的对象。
我该如何验证?必须将验证器服务注入(inject)我的对象中的 __construct 吗?
我的目标:
class Person
{
/**
* @var int
*
* @ORM\Column(name="id", type="guid")
* @ORM\Id
* @ORM\GeneratedValue(strategy="UUID")
* @expose
*/
private $id;
/**
* @var int
*
* @ORM\Column(name="name", type="string")
* @Assert\Email()
*/
private $email;
public function __construct($email, ValidatorInterface $validator){
$this->email = $email;
$validator->validate($this); // good practice ?
}
我的最终目标是对该实体的输入验证进行单元测试。
谢谢
编辑:
根据 Yonel 的回答,我在构造函数的末尾添加了以下内容:
$errors = $validator->validate($this);
if(count($errors) > 0) {
$errorsString = (string) $errors;
throw new InvalidArgumentException($errorsString);
}
这是一个好的做法吗?如果没有,为什么? 谢谢!
最佳答案
您强调的原则是关于应用程序的表示层,该应用程序可以使用可以验证用户输入的表单组件,然后该数据用于实例化实体。
在演示文稿的示例中,命名构造函数将表单作为参数,因此电子邮件地址的验证是通过表单完成的(验证用户输入)。
具有有效状态的对象的含义是指具有名称、姓氏和电子邮件均有效的 User 类型的对象(例如不为空)。
所以你可以拥有以下对象:
class User
{
private $name;
private $surname;
private $email;
private function __construct(string $name, string $surname, string $email)
{
$this->name = $name;
$this->surname = $surname;
$this->email = $email;
}
public static function create(string $name, string $surname, string $email): User
{
return new static($name, $surname, $email);
}
public function fromFormData(FormInterface $form):User
{
// The form validate user input (i.e. valid email address)
return self::create($form->get('name'), $form->get('surname'), $form->get('email'));
}
}
另一种方法可能是使用 DTO,或者您可以查看 this关于验证 DTO 对象的有用包。
希望这有帮助
关于php - 构造时的学说实体验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39641671/