简体   繁体   English

如何在我自制的服务中使用getContainer()

[英]How can I use the getContainer() in my self-made service

I would like to use EntityManager in self-made Service 我想在自制服务中使用EntityManager

in my config.yml 在我的config.yml中

services:
    myfunc:
        class:   Acme\TopBundle\MyServices\MyFunc
        arguments: []

in Acme\\TopBundle\\MyServices\\MyFunc.php 在Acme \\ TopBundle \\ MyServices \\ MyFunc.php中

namespace Acme\TopBundle\MyServices;
use Doctrine\ORM\EntityManager;

class MyFunc
{
    public $em;

    public function check(){
        $this->em = $this->getContainer()->get('doctrine')->getEntityManager(); // not work.
.
.

it shows error when I call method check(). 当我调用方法check()时它显示错误。

Call to undefined method Acme\TopBundle\MyServices\MyFunc::getContainer()

How can I use getContainer() in myFunc class?? 我怎样才能在myFunc类中使用getContainer()?

As you (fortunately) didn't inject the container in your myfunct service, there's no available reference to the container within your service. 由于您(幸运的是)没有在myfunct服务中注入容器,因此您的服务中没有可用的容器引用。

You may not neeed to get the entity manager via the service container! 您可能不需要通过服务容器获取实体管理器! Keep in mind that the DIC allows you to customise your services by injecting only the relevant services they need (the entity manager in your case) 请记住,DIC允许您通过仅注入所需的相关服务(在您的情况下为实体管理器)来自定义您的服务

namespace Acme\TopBundle\MyServices;

use Doctrine\ORM\EntityManager;

class MyFunc
{
    private $em;

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

    public function check()
    {
        $this->em // give you access to the Entity Manager

Your service definition, 你的服务定义,

services:
    myfunc:
        class:   Acme\TopBundle\MyServices\MyFunc
        arguments: [@doctrine.orm.entity_manager]

Also, 也,

  • Consider using "injection via setters" in case you're dealing with optional dependencies. 如果您正在处理可选的依赖项,请考虑使用“通过setter注入”。

You need to make MyFunc "container aware": 您需要使MyFunc“容器识别”:

namespace Acme\TopBundle\MyServices;

use Symfony\Component\DependencyInjection\ContainerAware;

class MyFunc extends ContainerAware // Has setContainer method
{
    public $em;

    public function check(){
        $this->em = $this->container->get('doctrine')->getEntityManager(); // not work.

Your service: 您的服务:

myfunc:
    class:   Acme\TopBundle\MyServices\MyFunc
    calls:
        - [setContainer, ['@service_container']]
    arguments: []

I should point out that injecting a container is usually not required and is frowned upon. 我应该指出,注射容器通常不是必需的,并且不赞成。 You could inject the entity manager directly into MyFunc. 您可以将实体管理器直接注入MyFunc。 Even better would be to inject whatever entity repositories you need. 更好的方法是注入您需要的任何实体存储库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM