Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to inject EntityManager into a service

While using Symfony 3.3, I am declaring a service like this:

class TheService implements ContainerAwareInterface
{
    use ContainerAwareTrait;
    ...
}

Inside each action where I need the EntityManager, I get it from the container:

$em = $this->container->get('doctrine.orm.entity_manager');

This is a bit annoying, so I'm curious whether Symfony has something that acts like EntityManagerAwareInterface.

like image 623
user3429660 Avatar asked Jun 28 '17 18:06

user3429660


1 Answers

Traditionally, you would have created a new service definition in your services.yml file set the entity manager as argument to your constructor

app.the_service:
    class: AppBundle\Services\TheService
    arguments: ['@doctrine.orm.entity_manager']

More recently, with the release of Symfony 3.3, the default symfony-standard-edition changed their default services.yml file to default to using autowire and add all classes in the AppBundle to be services. This removes the need for adding the custom service and using a type hint in your constructor will automatically inject the right service.

Your service class would then look like the following:

use Doctrine\ORM\EntityManagerInterface;

class TheService
{
    private $em;

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

    // ...
}

For more information about automatically defining service dependencies, see https://symfony.com/doc/current/service_container/autowiring.html

The new default services.yml configuration file is available here: https://github.com/symfony/symfony-standard/blob/3.3/app/config/services.yml

like image 186
Stephan van Leeuwen Avatar answered Sep 20 '22 06:09

Stephan van Leeuwen