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.

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

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP