我如何在自制服务中使用getContainer() [英] How can I use the getContainer() in my self-made service

查看:279
本文介绍了我如何在自制服务中使用getContainer()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在自己的服务中使用EntityManager

I would like to use EntityManager in self-made Service

在我的config.yml

in my config.yml

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

在Acme\TopBundle\MyServices\MyFunc.php

in 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.
.
.

当我调用方法check()时,它显示错误。

it shows error when I call method check().

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

如何在myFunc类中使用getContainer()?

How can I use getContainer() in myFunc class??

推荐答案

As你(幸运的是)没有将容器注入到您的 myfunct 服务中,没有可用的服务中的容器的引用。

As you (fortunately) didn't inject the container in your myfunct service, there's no available reference to the container within your service.

您不可以通过服务容器获取实体管理器!请记住,DIC允许您通过仅注射他们需要的相关服务(您的案例中的实体经理)来自定义您的服务。

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)

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

您的服务定义

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






另外,


Also,


  • 考虑使用通过设置器注入,以防您处理可选依赖关系。

这篇关于我如何在自制服务中使用getContainer()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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