Symfony 3 - how to introduce a validator into a service?

I am trying to introduce a validator into my service, but I cannot find it:

mybundle.service.supplier: class: AppBundle\Service\SupplierService calls: - [setValidator, ['@validator']] 

@validator is not an expected recursive Validator http://api.symfony.com/3.1/Symfony/Component/Validator/Validator/RecursiveValidator.html - @validator is an interface.

So how can I introduce a validator into my service?

This is what I want:

 <?php namespace AppBundle\Service; use AppBundle\Entity\Supplier; use AppBundle\Helper\EntityManagerTrait; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\Validator\Validator\RecursiveValidator; /** * Class SupplierService * @package AppBundle\Service */ class SupplierService { use EntityManagerTrait; /** @var RecursiveValidator $validator */ protected $validator; /** * @return RecursiveValidator */ public function getValidator() { return $this->validator; } /** * @param RecursiveValidator $validator * @return SupplierService */ public function setValidator($validator) { $this->validator = $validator; return $this; } public function addSupplier($data) { $supplier = new Supplier(); $validator = $this->getValidator(); $errors = $validator->validate($supplier); } } 
+5
source share
1 answer

@validator is an interface.

It does not make sense. If it is an interface, there cannot be an instacne Validator service. Yes, it implements ValidatorInterface , but it is not.

On the other hand, I'm sure you will get an instance of RecursiveValidator . See my analyzes:

  • Check the Validator definition in Symfony XML:

     <service id="validator" class="Symfony\Component\Validator\Validator\ValidatorInterface"> <factory service="validator.builder" method="getValidator" /> </service> 
  • Check the validator.builder factory service validator.builder :

     <service id="validator.builder" class="Symfony\Component\Validator\ValidatorBuilderInterface"> <factory class="Symfony\Component\Validator\Validation" method="createValidatorBuilder" /> <call method="setConstraintValidatorFactory"> <argument type="service" id="validator.validator_factory" /> </call> <call method="setTranslator"> <argument type="service" id="translator" /> </call> <call method="setTranslationDomain"> <argument>%validator.translation_domain%</argument> </call> </service> 
  • Check out the factory Symfony\Component\Validator\Validation::createValidatorBuilder . It returns an instance of ValidatorBuilder

  • Finally, check out ValidatorBuilder::getValidator() . It ends with the following:

     return new RecursiveValidator($contextFactory, $metadataFactory, $validatorFactory, $this->initializers); 

So, you will get the correct instance ( RecursiveValidator ).

Hope this helps ...

+7
source

Source: https://habr.com/ru/post/1258473/


All Articles