【问题标题】:How to use a second database for user authentication in Symfony2?如何在 Symfony2 中使用第二个数据库进行用户身份验证?
【发布时间】:2011-09-23 08:35:45
【问题描述】:

在我的 Symfony 2.0 应用程序中,我必须访问包含用户数据的第二个数据库。因此,我在 config_*.yml 中定义了两个数据库连接。我解决这个问题的方法是复制现有的 EntityUserProvider 并将其注册为 services.yml 中的服务,如下所示:

services:
    security.user.provider.concrete.acme_provider:
        class: Acme\MyappBundle\Security\Core\Authentication\Provider\AcmeUserProvider
        arguments: [@doctrine.orm.entity_manager, Acme\MyappBundle\Entity\Users, 'username']

到目前为止,这工作正常,除了它为我提供了默认的实体管理器。如何注入使用其他数据库连接的实体管理器?我想我必须将其设置为服务,但我不知道如何。

【问题讨论】:

    标签: php authentication symfony


    【解决方案1】:

    如果您想在服务中使用特定的 EntityManager,请将整个 Doctrine Registry 作为参数注入,如下所示:

    services:
    security.user.provider.concrete.acme_provider:
        class: Acme\MyappBundle\Security\Core\Authentication\Provider\AcmeUserProvider
        arguments: [@doctrine, Acme\MyappBundle\Entity\Users, 'username']
    

    然后,在您的服务构造函数中,影响您要用作类属性的 EntityManager:

    namespace Acme\MyappBundle\Security\Core\Authentication\Provider;
    
    use Symfony\Bundle\DoctrineBundle\Registry;
    // ....
    
    class AcmeUserProvider implements UserProviderInterface
    {
        private $em;
        // ...
    
        public function __construct(Registry $doctrine, $class, $property)
        {
            $this->em = $doctrine->getEntityManager('your_em');
            // ....
        }
    
        // ....
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-12
      • 2013-02-24
      • 1970-01-01
      • 2014-09-25
      • 1970-01-01
      • 2013-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多