Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

autowired - How to use Symfony autowiring with multiple entity managers

I would like to use the autowiring in a service that use 2 different entity manager. How to achieve something like that ?

use DoctrineORMEntityManager;
class TestService
{
    public function __construct(EntityManager $emA, EntityManager $emB)
    {
    }
}

My service.yml file use to be configured like that :

    app.testservice:
        class: AppServicesTestService
        arguments:
            - "@doctrine.orm.default_entity_manager"
            - "@doctrine.orm.secondary_entity_manager"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are already two good answers posted but I'd like to add a third as well as some context to help chose which approach to use in a given situation.

emix's answer is very simple but a bit fragile in that it relies on the name of the argument for injecting the correct service. Which is fine but you won't get any help from your IDE and sometimes might be a bit awkward. The answer should probably use EntityManagerInterface but that is a minor point.

DynlanKas's answer requires a bit of code in each service to locate the desired manager. It's okay but can be a bit repetitive. On the other hand, the answer is perfect when you don't know in advance exactly which manager is needed. It allows you to select a manager based on some dynamic information.

This third answer is largely based on Ron's Answer but refined just a bit.

Make a new class for each entity manager:

namespace AppEntityManager;
use DoctrineORMDecoratorEntityManagerDecorator;
class AEntityManager extends EntityManagerDecorator {}
class BEntityManager extends EntityManagerDecorator {}

Don't be alarmed that you are extending a decorator class. The class has the same interface and the same functionality as a 'real' entity manager. You just need to inject the desired manager:

# config/services.yaml
AppEntityManagerAEntityManager:
    decorates: doctrine.orm.a_entity_manager

AppEntityManagerBEntityManager:
    decorates: doctrine.orm.b_entity_manager

This approach requires making a new class for each entity manager as well as a couple of lines of configuration, but allows you to simply typehint against the desired class:

public function __construct(AEntityManager $emA, BEntityManager $emB)
{
}

It is, arguably, the most robust and standard way to approach the original question.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...