Symfony自定义验证器作为服务

时间:2015-08-11 12:44:32

标签: php validation symfony symfony-2.3

尝试按照官方文档中的自定义验证程序作为服务示例。我已将我的验证器定义为我的" services.yml":

中的服务
cf.validator.unique.in.system:
            class: 'CF\AppBundle\Validator\Constraints\UniqueInSystemValidator'
            arguments: ['@doctrine']
            tags:
                - { name: 'validator.constraint_validator', alias: 'cf.validator.unique.in.system' }

我已经创建了必要的约束和验证器类:

约束

namespace CF\AppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */
class UniqueInSystem extends Constraint
{
    public $message = 'This value is already used.';

    public function getTargets()
    {
        return self::CLASS_CONSTRAINT;
    }

    public function validatedBy()
    {
        return 'cf.validator.unique.in.system';
    }
}

验证

namespace CF\AppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Doctrine\Bundle\DoctrineBundle\Registry as Doctrine;

/**
 * @Annotation
 */
class UniqueInSystemValidator extends ConstraintValidator
{
    protected  $em;

    public  function  __construct(Doctrine $doctrine)
    {
        $this->em = $doctrine->getManager();
    }
    public function validate($subsystem, Constraint $constraint)
    {

        1==1; // here is a breakpoint by now
//        $this->context->addViolationAt('[expiresAt].expiresAt', $constraint->message, ['%string%' => $value->format('Y-m-d')] );
    }

我不明白,是我收到的错误消息:FatalErrorException: Error: Class '\Symfony\Component\Validator\Constraints\CF\AppBundle\Validators\Constraints\UniqueInSystem' not found in /var/www/escritorio.dev/application/vendor/symfony/symfony/src/Symfony/Component/Validator/Mapping/Loader/AbstractLoader.php line 89

特别是这部分:'\Symfony\Component\Validator\Constraints\CF\AppBundle\Validators\Constraints\UniqueInSystem'。为什么symfony试图在这个奇怪的命名空间中搜索?如何避免这个问题?

UPD

验证器本身通过/src/CF/AppBundle/Resources/config/validation.yml

应用
CF\AppBundle\Entity\SubSystem:
  constraints:
      - CF\AppBundle\Validators\Constraints\UniqueInSystem: ~
  properties:
    name:
      - NotBlank: ~
      - Length:
          max: 100
    owner:
      - NotBlank: ~
    leader:
      - NotBlank: ~
    system:
      - NotBlank: ~
    status:
      - NotBlank : ~
      - Type:
          type: integer

app/console container:debug输出:

$ php app/console container:debug  | grep CF
auc_helper                                         container CF\AppBundle\Services\AucHelper
cf.validator.unique.in.system                      container CF\AppBundle\Validator\Constraints\UniqueInSystemValidator

1 个答案:

答案 0 :(得分:8)

// This
CF\AppBundle\Entity\SubSystem:
  constraints:
    - CF\AppBundle\Validators\Constraints\UniqueInSystem: ~

// Should be
CF\AppBundle\Entity\SubSystem:
  constraints:
    - CF\AppBundle\Validator\Constraints\UniqueInSystem: ~

为什么Constraints目录不被称为Constraint总是有点神秘。但Validator一直被称为Validator。