How can I use the getContainer() in my self-made s

2019-06-14 14:57发布

I would like to use EntityManager in self-made Service

in my config.yml

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

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

it shows error when I call method check().

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

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

2条回答
Explosion°爆炸
2楼-- · 2019-06-14 15:13

You need to make MyFunc "container aware":

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. Even better would be to inject whatever entity repositories you need.

查看更多
别忘想泡老子
3楼-- · 2019-06-14 15:26

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

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

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.
查看更多
登录 后发表回答