duanjumie8753 2016-11-15 04:08
浏览 46
已采纳

如何使用Symfony组件配置自定义验证器的依赖项?

I am using Symfony Validator and Symfony Service Container in a project, but not the full Symfony Framework.

I have written a custom validator that requires some dependencies to be supplied as constructor arguments.

The Symfony Documentation describes a method of configuring the validator as service, which I have done successfully. But then it makes of point of using the validator.constraint_validator service tag, which I suspect glues them together.

This service tag seems to be specific to when using the full Symfony Framework -- Symfony Validator is not magically loading my custom validator when I add this tag (unsurprisingly.)

So, how can I link the Validator and Service Container components? Or is there any other strategy for having Symfony Validator to load my customer validator with dependencies?

  • 写回答

1条回答 默认 最新

  • dourangdz750379 2016-11-15 08:25
    关注

    You are right, this tag (validator.constraint_validator) processed by compiler-pass from Symfony/FrameworkBundle. If you don't want to use this bundle, but you want to link DI container with validator, you should re-implement this process.

    First, we need an instance of ConstraintValidatorFactoryInterface. Default implementation just looks for a class, with name returned by validatedBy() method of constraint. Implementation from FrameworkBundle considers result of validatedBy() as service identifier/or tag alias and gets this service from container. Our implementation should do something like that:

    use Symfony\Component\DependencyInjection\ContainerInterface;
    
    use Symfony\Component\Validator\ConstraintValidatorFactoryInterface;
    use Symfony\Component\Validator\Constraint;
    
    class ContainerConstraintValidatorFactory implements ConstraintValidatorFactoryInterface
    {
        private $container;
    
        public function __construct(ContainerInterface $container)
        {
            $this->container = $container;
        }
    
        public function getInstance(Constraint $constraint)
        {
            // Simplified implementation, just for example:
            return $this->container->get($constraint->validatedBy());
        }
    }
    

    For example, suppose we have some custom validation constraint and validator class with some dependency:

    use Symfony\Component\Validator\Constraint;
    use Symfony\Component\Validator\ConstraintValidator;
    
    class CustomConstraint extends Constraint
    {
        public $message = 'Oops!';
    
        public function validatedBy()
        {
            return 'validator.custom';
        }
    }
    
    class CustomConstraintValidator extends ConstraintValidator
    {
        private $dependency;
    
        public function __construct($dependency)
        {
            $this->dependency = $dependency;
        }
    
        public function validate($value, Constraint $constraint)
        {
            if (rand() % 2 === 0) {
                $this->context
                    ->buildViolation($constraint->message)
                    ->addViolation();
            }
        }
    }
    

    Next we register constraint validator as service with ID same as result of validatedBy() method from related constraint object. We create instance of the validator service related with container through this factory. All constraints validators, registered as same manner will be available.

    use Symfony\Component\DependencyInjection\ContainerBuilder;
    use Symfony\Component\Validator\Validation;
    
    $container = new ContainerBuilder();
    $container->register(
        'validator.custom', 
        new CustomConstraintValidator('Some dependency value')
    );
    
    $validatorBuilder = Validation::createValidatorBuilder();
    $validatorBuilder->setConstraintValidatorFactory(
        new ContainerConstraintValidatorFactory($container)
    );
    $validator = $validatorBuilder->getValidator();
    
    $violations = $validator->validate('test value', [ 
        new CustomConstraint() 
    ]);
    

    It works, however I recommend to consider of using FrameworkBundle to not reinvent the wheel. You can configure it to use only things that you need.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器