Is there a way to inject EntityManager into a service

折月煮酒 提交于 2019-12-19 03:19:11

问题


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.


回答1:


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




回答2:


Sometimes I inject the EM into a service on the container like this in services.yml:

 application.the.service:
      class: path\to\te\Service
      arguments:
        entityManager: '@doctrine.orm.entity_manager'

And then on the service class get it on the __construct method. Hope it helps.



来源:https://stackoverflow.com/questions/44809739/is-there-a-way-to-inject-entitymanager-into-a-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!