2

我的验证器服务未提供给验证器。我收到一个错误:“警告:My\Bundle\Validator\Constraints\MyCustomValidator::__construct() 缺少参数 1...”

这是我的 services.yml

// My\Bundle\Resources\config\services.yml
services:
    my.validator.service:
        class: My\Bundle\Validator\Constraints\MyCustomValidator
        arguments: [ @doctrine.orm.entity_manager ]

这是我的验证器类:

// My\Bundle\Validator\Constraints\MyCustomValidator
namespace My\Bundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use Doctrine\ORM\EntityManager;

class MyCustomValidator extends ConstraintValidator
{
    private $em;

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

    public function validate($value, Constraint $constraint)
    {
        // Do something
    }
}

这是我的验证.yml

// My\Bundle\Resources\config\validation.yml
My\Bundle\Entity\Page:
    properties:
        name:
            - NotBlank: ~
            - My\Bundle\Validator\Constraints\MyCustom: ~

这是我的约束类

namespace My\Bundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

class MyCustom extends Constraint
{
    public $message = 'Something is wrong with "%string%".';

    public function validatedBy()
    {
        return get_class($this) . 'Validator';
    }
}

如果有人可以帮助我,我将不胜感激。

我也尝试将参数名称更改为“@doctrine.orm.default_entity_manager”,但没有运气。

4

2 回答 2

5

问题是我的 services.yml。因为该服务被用作验证器,所以我必须使用 validator.constraint_validator 标记。这是在文档中。哎呀!

services:
    my.validator.service:
        class: My\Bundle\Validator\Constraints\MyCustomValidator
        arguments: [ @doctrine.orm.entity_manager ]
        tags:
            - { name: validator.constraint_validator, alias: my_custom_alias}

我还需要重写 Constraint 类的validateBy() 方法,以便它返回上面的别名,例如:

// My\Bundle\Validator\Constrains\MyCustom.php
public function validatedBy()
{
    return 'my_custom_alias';
}
于 2013-04-30T11:19:41.970 回答
0

您应该将原则注册表传递给您的服务并使用它来检索实体管理器实例。

将您的构造函数更改为:

public function __construct(RegistryInterface $registry)
{
    $this->registry = $registry;
}

然后将您的服务配置修改为:

// My\Bundle\Resources\config\services.yml
services:
    my.validator.service:
        class: My\Bundle\Validator\Constraints\MyCustomValidator
        arguments: [ @doctrine ]

现在,只要您需要加入实体经理,MyCustomValidator您就可以执行此操作

$em = $this->registry->getManager()
于 2013-04-29T15:20:41.787 回答