学说2验证

Rob*_*toq 6 php validation unique doctrine-orm

我有验证问题.在Doctrine 1中我使用了这个:

if ($model->isValid()) {
    $model->save();
} else {
    $errorStack = $model->getErrorStack();
    ...
}
Run Code Online (Sandbox Code Playgroud)

并在$ errorStack中我得到了列名和错误消息.但是在Doctrine 2中我可以使用它:

实体

/**
 * @PrePersist @PreUpdate
 */
public function validate()
{
    if ($this->name == null)) {
        throw new \Exception("Name can't be null"); 
    }
}
Run Code Online (Sandbox Code Playgroud)

控制器:

try {
    $user = new \User();
    //$user->setName('name');
    $user->setCity('London');
    $this->_entityManager->persist($user); 
    $this->_entityManager->flush();
} catch(Exception $e) {
    error_log($e->getMessage());
} 
Run Code Online (Sandbox Code Playgroud)

但我有两个问题:

  • 我不知道哪一列?
  • 我不想手动检查唯一

如果我从实体中跳过validate(),那么将捕获唯一(来自此error.log)

Unique violation: 7 ERROR:  duplicate key value violates unique constraint "person_email_uniq"
Run Code Online (Sandbox Code Playgroud)

但是例如用户保存2条记录,第一条是错误的,但第二条有效,第一次保存后EntityManager将关闭,因为"EntityManager已关闭",我无法保存第二条(好)记录.

哪个是这个问题的最佳解决方案?

Wiz*_*rdZ 3

在 D2 中进行验证的方法有几种: - 与您在帖子中描述的一个实体相关的业务逻辑 - 基于侦听器的验证,请检查http://www.doctrine-project.org/docs/orm/2.0/en/ Reference/events.html#preupdate, ValidCreditCardListener 示例 - 基于第三方库的验证,此处描述的内容类似: Zend_Validate_Db_RecordExists with Doctrine 2? Zend_Validate: Db_NoRecordExists 与 Doctrine 如果您使用特定的框架进行表单渲染,您可以将验证集成到其中。

我在实体中使用了与一个实体相关的业务逻辑的验证:

/**
 * @PrePersist @PreUpdate
 */
public function validate()
{
    $this->errors = array();
    if ($this->name == null)) {
        $this->errors['name'][] = 'Something wrong'; 
    }
    if (0 < count($errors)) {
        throw new Exception('There are errors');
    }
}

public function getErrors()
{
   return $this->errors;
}
Run Code Online (Sandbox Code Playgroud)

和侦听器验证强制执行某些规则,例如唯一性,因为在我的应用程序中,实体不仅可以基于表单创建。