【问题标题】:Doctrine 2 validation原则 2 验证
【发布时间】:2011-05-21 15:51:13
【问题描述】:

我的验证有问题。在教义 1 中,我使用了这个:

if ($model->isValid()) {
    $model->save();
} else {
    $errorStack = $model->getErrorStack();
    ...
}

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

实体

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

控制器:

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

但我有两个问题:

  • 我不知道是哪一栏?
  • 我不想手动检查唯一性

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

Unique violation: 7 ERROR:  duplicate key value violates unique constraint "person_email_uniq"

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

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

【问题讨论】:

    标签: php validation unique doctrine-orm


    【解决方案1】:

    在 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 with 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;
    }
    

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

    【讨论】:

      【解决方案2】:

      记得在实体中定义@HasLifecycleCallbacks。

      /**
       * @Entity @Table(name="songs") @HasLifecycleCallbacks
       */
      class Song
      {
         ...
         /** @PrePersist @PreUpdate */
          public function doStuffOnPreUpdatePrePersists()
          {
            ...
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-19
        • 1970-01-01
        • 1970-01-01
        • 2013-02-05
        • 2018-04-16
        • 1970-01-01
        相关资源
        最近更新 更多