Alex Rivera | Logout

How to inject validator in Symfony

Asked 2012-09-17T15:46:31.057
10

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

1 Answer

14

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;
}
answered 2012-09-17T16:07:20.207

Your Answer