How to implement a validator in symfony

Can someone show me how I will inject a validator into a regular class using dependency injection.

In my controller, I:

use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Form; class FormController extends Controller { public function indexAction() { $form = new Form(); $email = $request->request->get('email'); $valid = $form->isValid($email); } } 

and I want to use this custom class, but I need it to gain access to the validator.

 class Form { public function isValid($value) { // This is where I fail $validator = $this->get('validator'); ... etc } } 
+6
source share
4 answers

To do this, your custom class must be defined as a service, and you will access it from the controller using $form = $this->get('your.form.service'); instead of creating it directly.

When defining a service, make sure you enter the validation service:

 your.form.service: class: Path\To\Your\Form arguments: [@validator] 

Then you need to handle this in the method of building the form service:

 /** * @var \Symfony\Component\Validator\Validator */ protected $validator; function __construct(\Symfony\Component\Validator\Validator $validator) { $this->validator = $validator; } 
+12
source

From symfony2.5 to

Validator is called RecursiveValidator , so for injection

 use Symfony\Component\Validator\Validator\RecursiveValidator; function __construct(RecursiveValidator $validator) { $this->validator = $validator; } 
+3
source

The Form class can inherit from ContainerAware (Symfony \ Component \ DependencyInjection \ ContainerAware). Then you will have access to the container, and you can get the validator service as follows:

 $validator = $this->container->get('validator'); 
0
source

In Symfony 4+, if you use the default configuration (with auto-connect enabled), the easiest way is to implement ValidatorInterface .

For instance:

 <?php use Symfony\Component\Validator\Validator\ValidatorInterface; class MySuperClass { private $validator; public function __construct( ValidatorInterface $validator ) { $this->validator = $validator; } 
0
source

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


All Articles