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
}
}
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:
Then you’ll need to handle this in the construct method of your Form service: