自定义验证器和依赖注入

自定义验证器和依赖注入

本文介绍了Symfony2-自定义验证器和依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图对依赖验证器使用依赖注入,以便能够使用entityManager。

I am trying to use dependancy injection for a custom validator, in order to be able to use the entityManager.

我遵循了Symfony示例:,但是我总是收到此错误消息:

I followed the Symfony Example: Dependency Injection, but I am allways getting this error message:

这是我的课程:

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"

我在哪里错了?谢谢您的帮助。

Where am I wrong? Thank you for your help.

推荐答案

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

You have wrong service file, when You add tags and alias you could use "isdoi" name

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

这篇关于Symfony2-自定义验证器和依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 21:30