Symfony2 - 自定义验证器和依赖注入

时间:2013-07-16 08:15:57

标签: php symfony dependency-injection customvalidator

我正在尝试对自定义验证器使用依赖注入,以便能够使用entityManager。

我按照Symfony示例:Dependency Injection,但我总是收到此错误消息:

  

FatalErrorException:错误:找不到类'isdoi'   /home/milos/workspace/merrin3/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Validator/ConstraintValidatorFactory.php   第68行

以下是我的课程:

1。 IsDOI课程:

    <?php
    namespace Merrin\MainBundle\Validator\Constraints;
    use Symfony\Component\Validator\Constraint;

    /**
     * @Annotation
    */
    class IsDOI extends Constraint
    {
    public $message_publisher_DOI = 'The Publisher DOI abbreviation does not correspond to the DOI you filled in !';
    public $message_journal_DOI = 'No journal found with the DOI you filled in !';
    public $journal;
    public $doiAbbreviation;

     public function validatedBy() {
            return "isdoi";
        }

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

2。 IsDOIValidator类:

<?php

namespace Merrin\MainBundle\Validator\Constraints;

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

class IsDOIValidator extends ConstraintValidator
{
    private $entityManager;

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

    public function validate($value, Constraint $constraint)
    {       
        $em_mdpipub = $this->entityManager('mdpipub');
        //Do some tests here...

    }
}

第3。服务:

merrin.main.validator.isdoi:
    class:  Merrin\MainBundle\Validator\Constraints\IsDOIValidator
    arguments: 
        entityManager: "@doctrine.orm.entity_manager"

我哪里错了?谢谢你的帮助。

2 个答案:

答案 0 :(得分:7)

您的服务文件错误,当您添加标签和别名时,您可以使用“isdoi”名称

merrin.main.validator.isdoi:
    class:  Merrin\MainBundle\Validator\Constraints\IsDOIValidator
    arguments: 
        entityManager: "@doctrine.orm.entity_manager"
    tags:
        - { name: validator.constraint_validator, alias: isdoi }

答案 1 :(得分:3)

您告诉Symfony2您的约束的验证程序类是isdoivalidateBy method)。但是,您的验证工具为IsDOIValidator

您必须使用:

public function validateBy()
{
    return "IsDOIValidator";
}

但是,如果您的Constraint班级名称为IsDOI,Symfony会自动将IsDOIValidator视为ConstraintValidatorvalidateBy的默认行为是将“Validator”附加到约束名称,并查找具有此名称的类。因此,如果您不重载validateBy,Symfony2将自动搜索IsDOIValidator