user623520
user623520

Reputation:

How to inject validator in Symfony

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
    }
}

Upvotes: 10

Views: 7105

Answers (4)

magnetik
magnetik

Reputation: 4431

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;
    }

Upvotes: 4

DonCallisto
DonCallisto

Reputation: 29912

From Symfony2.5 on

Validator is called RecursiveValidator so, for injection

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

Upvotes: 3

Carlos Granados
Carlos Granados

Reputation: 11351

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');

Upvotes: 0

RobMasters
RobMasters

Reputation: 4148

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;
}

Upvotes: 14

Related Questions