whitebear
whitebear

Reputation: 12423

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

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

Upvotes: 1

Views: 4659

Answers (2)

Ahmed Siouani
Ahmed Siouani

Reputation: 13891

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.

Upvotes: 3

Cerad
Cerad

Reputation: 48865

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.

Upvotes: 0

Related Questions