如何在表单构建器symfony中添加获取容器? [英] How Can I add get container in form builder symfony?

查看:145
本文介绍了如何在表单构建器symfony中添加获取容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在表单构建器symfony中添加get容器?

我想在表单构建器中使用$ get-> container ...

解决方案

将整个容器注入表单类型是一种不好的做法。请考虑仅向您的表单类型注入必需的依赖项。您可以简单将表单类型定义为服务并注入所需的依赖关系。



src / AppBundle / Form / TaskType.php

 使用Doctrine \\ \\ORM\EntityManagerInterface; 
// ...

类TaskType扩展AbstractType
{
private $ em;

public function __construct(EntityManagerInterface $ em)
{
$ this-> em = $ em;
}

// ...
}

src / AppBundle / Resources / config / services.yml

 服务:
AppBundle \Form \TaskType :
arguments:['@ doctrine.orm.entity_manager']
标签:[form.type]






要注入一个存储库类,有两种方法。第二种方法更干净。



注入EntityManager类并从EM获取存储库类:

  $ this-> em-> getRepository(User :: class)

将存储库类注册为服务使用EM工厂并将其注入到您的表单类型:

  services:
AppBundle \ Repository \UserRepository:
工厂:['@ doctrine.orm.entity_manager',getRepository] ​​
参数:['AppBundle \Entity\User']


How Can I add get container in form builder symfony ?

I would like use $get->container in form builder...

解决方案

Injecting the whole container into a form type is a bad practice. Please consider injecting only required dependencies to your form type. You can simply define your form type as a service and inject required dependencies.

src/AppBundle/Form/TaskType.php

use Doctrine\ORM\EntityManagerInterface;
// ...

class TaskType extends AbstractType
{
    private $em;

    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    // ...
}

src/AppBundle/Resources/config/services.yml

services:
    AppBundle\Form\TaskType:
        arguments: ['@doctrine.orm.entity_manager']
        tags: [form.type]


To inject a repository class there are two ways. The second approach is more clean.

Inject an EntityManager class and get repository class from EM:

$this->em->getRepository(User::class)

Register repository class as a service using EM factory and inject it to your form type:

  services:
    AppBundle\Repository\UserRepository:
      factory: ['@doctrine.orm.entity_manager', getRepository]
      arguments: ['AppBundle\Entity\User']

这篇关于如何在表单构建器symfony中添加获取容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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