Dependency Inject non-default Entity Manager into Service in Symfony

后端 未结 1 1487
花落未央
花落未央 2021-01-06 22:51

I want to change from the default em to an em called \'ps\'. The configuration is correct and in the controller I can simply type $this->getManager(\'ps\')->getC

相关标签:
1条回答
  • 2021-01-06 23:30

    If your service class just needs the connection then it easiest way it make your own connection class and inject it.

    namepace AppBundle\Connection;
    
    class PsConnection extends Doctrine\DBAL\Connection
    {
    }
    
    # doctrine.yaml
    doctrine:
        dbal:
            connections:
                ps:
                    wrapper_class: AppBundle\Connection\PsConnection
    
    class HilaService
    {
        public function __construct(AppBundle\Connection\PsConnection $conn)
    

    Everything will work as before but you can get the connection directly.

    if you really do need the entity manager then you can make a service definition:

    # services.yaml
    AppBundle\Service\HilaService:
        $entityManager: '@doctrine.orm.ps_entity_manager'
    

    Finally, if you don't want to fool around with any of this stuff you can inject the ManagerRegistry and pull what you need from it.

    class HilaService
    {
        public function __construct(Doctrine\Common\Persistence\ManagerRegistry $managerRegistry)
        {
            $em = $managerRegistry->getManager('ps'); // or getConnection()
    
    0 讨论(0)
提交回复
热议问题