【问题标题】:Silex/Symfony Form validator : ensure a value is uniqueSilex/Symfony 表单验证器:确保值是唯一的
【发布时间】:2014-01-01 17:24:36
【问题描述】:

我将 Silex 与表单和验证器提供程序一起使用。

我有一个非常简单的注册表:

  • 用户名
  • 密码
  • 密码确认

用户名必须是唯一的,如何检查?

这是我的代码:

$form = $app['form.factory']->createBuilder('form')
      ->add('username', 'text', array(
        'constraints' => array(
          new Assert\NotBlank(),
          new Assert\Length(array('min' => 6, 'max' => 20)))
        ))
      ->add('password', 'repeated', array(
        'constraints' => array(
          new Assert\NotBlank(),
          new Assert\Length(array('min' => 6, 'max' => 20))
          )
        ))
      ->getForm();

使用 Symfony,我知道有 UniqueEntity 约束,但它带有 Doctrine,我只使用 Doctrine DBAL(Silex 提供者)

我想我可以使用 Callback 约束,但我想知道是否有比使用 SQL 查询编写回调更好的解决方案...或编写我自己的 Constraint 对象

谢谢

【问题讨论】:

  • 不是真正的重复,我要求实现我的目标的“最佳”方式:“在字段上添加约束以检查值是否唯一”。我在我的问题中提到了两种方式:创建自己的约束或使用回调。哪一个是最好的 ?还有其他方法吗?

标签: php forms validation symfony silex


【解决方案1】:

好的,我决定创建自己的约束,因为我可以将它重用于电子邮件。 所以,这是我的实现:

UniqueEntry.php:

<?php
/**
 * Ensure a value is unique in the database
 *
 * @author Thomas KELLER
 */

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\MissingOptionsException;
use Symfony\Component\Validator\Exception\InvalidArgumentException;

/**
 * @Annotation
 */
class UniqueEntry extends Constraint {

  public $notUniqueMessage = 'This value already exist in the database';
  public $dbal_connection;
  public $table;
  public $field;

  public function __construct($options = null)
  {
    parent::__construct($options);

    if ($this->dbal_connection === null)
      throw new MissingOptionsException(sprintf('The option "dbal_connection" is mandatory for constraint %s', __CLASS__), array('dbal_connection'));

    if (!$this->dbal_connection instanceof \Doctrine\DBAL\Connection)
      throw new InvalidArgumentException(sprintf('The option "dbal_connection" must be an instance of Doctrine\DBAL\Connection for constraint %s', __CLASS__));

    if ($this->table === null)
      throw new MissingOptionsException(sprintf('The option "table" is mandatory for constraint %s', __CLASS__), array('table'));

    if (!is_string($this->table) OR $this->table == '')
      throw new InvalidArgumentException(sprintf('The option "table" must be a valid string for constraint %s', __CLASS__));

    if ($this->field === null)
      throw new MissingOptionsException(sprintf('The option "field" is mandatory for constraint %s', __CLASS__), array('field'));

    if (!is_string($this->field) OR $this->field == '')
      throw new InvalidArgumentException(sprintf('The option "field" must be a valid string for constraint %s', __CLASS__));
  }
}

UniqueEntryValidator.php:

<?php
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class UniqueEntryValidator extends ConstraintValidator
{
  public function validate($value, Constraint $constraint)
  {
    $query = sprintf('SELECT `%s` FROM `%s` WHERE `%s` = ?',
      $constraint->field,
      $constraint->table,
      $constraint->field);

    $stmt = $constraint->dbal_connection->executeQuery($query, array($value));

    if ($stmt->fetch())
      $this->context->addViolation($constraint->notUniqueMessage);
  }
}

我发布我的实现以提出建议,请随时发表评论;)

【讨论】:

  • 实现这一点的更简单的方法是使用Callback constraint,传入一个函数,如:array('models\User', 'validateEmailUniqueness')。这并不是很简单,但我发现定义两个新类只是为了创建一个验证器有点令人厌烦。
  • 我认为有一些优点:更容易重用(您不必在所有控制器中重复代码),控制器中的代码更少,本着 Silex 的精神(遵循其他验证器约定)跨度>
  • 你也可以使用FormEvents like POST_SUBMIT 看看BoltCMS 源代码(对于v1.6.x 和v2.x )
猜你喜欢
  • 2011-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-16
  • 1970-01-01
  • 1970-01-01
  • 2016-09-04
  • 2015-01-23
相关资源
最近更新 更多