Symfony 3 - EntityManager dependency injection with multiple db connections
You can extend Doctrine's EntityManagerDecorator
, which implements EntityManagerInterface
and accepts an instance of EntityManager
in its constructor.
First extend the EntityManagerDecorator
class once for each of your connections.
namespace MyBundle\Service\Database;use Doctrine\ORM\Decorator\EntityManagerDecorator;class PrismEntityManager extends EntityManagerDecorator {}class BaanEntityManager extends EntityManagerDecorator {}
Then in your service configuration, you need to manually wire these two services.
MyBundle\Service\Database\PrismEntityManager: arguments: $wrapped: '@doctrine.orm.prism_entity_manager'MyBundle\Service\Database\BaanEntityManager: arguments: $wrapped: '@doctrine.orm.baan_entity_manager'
Now you just have to type-hint for one of these services.
public function __construct(FormFactoryInterface $formFactory, PrismEntityManager $em, RouterInterface $router){ $this->formFactory = $formFactory; $this->em = $em; $this->router = $router;}
I don't know if i understood your question correctly or not but you can set different configurations for different database connection as below:
dbal: default_connection: default connections: default: driver: pdo_mysql host: "%database_host%" port: "%database_port%" dbname: "%database_name%" user: "%database_user%" password: "%database_password%" charset: UTF8 mapping_types: enum: smallint custom: driver: pdo_mysql host: '%database_host2%' port: '%database_port2%' dbname: '%database_name2%' user: '%database_user2%' password: '%database_password2%' charset: UTF8 mapping_types: enum: smallint orm: default_entity_manager: default auto_generate_proxy_classes: "%kernel.debug%" entity_managers: auto_mapping: true default: naming_strategy: doctrine.orm.naming_strategy.underscore connection: default mappings: EntityBundle: type: annotation alias: DBAlias custom: naming_strategy: doctrine.orm.naming_strategy.underscore connection: custom mappings: EntityBundle: type: annotation alias: DBAlias
Now you can passed your custom EntityManager using doctrine.orm.custom_entity_manager
.
I think, I had the same issue with DBAL Connections as you have with EntityManager. I have solved this issue with some proxy class - described in this answer:https://stackoverflow.com/a/46265170/6357312
Any question let me know.