Symfony将实体管理器注入自定义验证器

时间:2015-04-11 13:47:42

标签: symfony doctrine entity entitymanager inject

在我的symfony应用程序中,我需要一个自定义验证约束,该约束应检查电子邮件是否唯一。 此约束应该用作注释。

我遵循symfony cookbook的指南,但我得到例外:

尝试加载类" unique.email.validator"来自全局命名空间。 你忘记了"使用"声明吗

这是我在Unique Email Constraint类中的代码:

<?php

namespace MyApp\AppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
* Class UniqueEmail
* @package MyApp\AppBundle\Validator\Constraints
* @Annotation
*/
class UniqueEmail extends Constraint
{
  public $message = 'The Email already exists.';

  public function validatedBy()
  {
      return 'unique.email.validator';
  }
}

这是我独特的EmailValidator的代码:

namespace MyApp\AppBundle\Validator\Constraints;

use Doctrine\ORM\EntityManager;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class UniqueEmailValidator extends ConstraintValidator
{
   /**
    * @var EntityManager
    */
   protected $em;

   public function __construct(EntityManager $entityManager)
   {
      $this->em = $entityManager;
   }

  public function validate($value, Constraint $constraint)
  {
      $repository = $this->em->getRepository('AppBundle:Advertiser');
      $advertiser = $repository->findOneBy(array(
          'email' => $value
      ));

      if ($advertiser) {
          $this->context->buildViolation($constraint->message)
              ->addViolation();
      }
  }
} 

最后但并非最不重要的是我的services.yml:

   services:
       unique.email.validator:
           class: MyApp\AppBundle\Validator\Constraints\UniqueEmailValidator
           arguments:
               entityManager: "@doctrine.orm.entity_manager"
           tags:
               - { name: validator.constraint_validator, alias:      unqiue.email.validator }

有没有人有任何想法如何解决它?

1 个答案:

答案 0 :(得分:6)

在您的services.yml中,别名拼写错误:'unqiue.email.validator'而不是'unique.email.validator'