How to inject validator in Symfony

最后都变了- 提交于 2020-01-03 07:32:14

问题


Can somebody show me how I would inject validator into a regular class using dependency injection.

In my controller I have :

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 got have access to validator.

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

回答1:


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

When defining your service, make sure to inject the validator service:

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

Then you'll need to handle this in the construct method of your Form service:

/**
 * @var \Symfony\Component\Validator\Validator
 */
protected $validator;

function __construct(\Symfony\Component\Validator\Validator $validator)
{
    $this->validator = $validator;
}



回答2:


From Symfony2.5 on

Validator is called RecursiveValidator so, for injection

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



回答3:


In Symfony 4+, if you use the default configuration (with auto wiring enabled), the easiest way is to inject a ValidatorInterface.

For instance:

<?php

use Symfony\Component\Validator\Validator\ValidatorInterface;

class MySuperClass
{
    private $validator;

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



回答4:


Your Form class can inherit from ContainerAware (Symfony\Component\DependencyInjection\ContainerAware). Then you will have access to the container and you will be able to get the validator service like this:

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


来源:https://stackoverflow.com/questions/12462770/how-to-inject-validator-in-symfony

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!