如何在Symfony中注入验证器 [英] How to inject validator in Symfony

查看:75
本文介绍了如何在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
    }
}


推荐答案

为此,您需要将自定义类定义为服务,然后您可以使用 $ form = $ this-> get(' your.form.service'); 而不是直接实例化它。

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]

然后,您需要在Form服务的构造方法中处理此问题:

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

这篇关于如何在Symfony中注入验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆