简体   繁体   English

Symfony 4动态数据库连接和FOS用户

[英]Symfony 4 dynamic database connection & FOS User

Using Symfony 4 , we are building a multi-customer application where each customer has a dedicated database. 使用Symfony 4 ,我们正在构建一个多客户应用程序 ,其中每个客户都有一个专用的数据库。 Customer databases are created automatically on-demand when new Customer is created. 创建新客户时,将自动按需创建客户数据库。 During this process, we create unique extra .env file (customer specific) which holds the database connection credentials. 在此过程中,我们将创建唯一的额外.env文件(特定于客户),该文件包含数据库连接凭据。

We have 2x database connection & 2x entity managers - common & customer . 我们有2x数据库连接和2x实体管理器commoncustomer customer entity manager is the default one in fact. customer实体经理实际上是默认的。 Obviously, customer entity manager does not have the correct connection params at first. 显然, customer实体经理一开始没有正确的连接参数。 We load the extra .env file accordingly (eg based on the domain) on kernel request and set the customer connection and entity manager accordingly: 我们根据内核请求相应地(例如基于域)加载额外的.env文件,并相应地设置customer连接和实体管理器:

$connection = $this->entityManager->getConnection();
$connection->close();

$reflectionConn   = new \ReflectionObject($connection);
$reflectionParams = $reflectionConn->getProperty('params');
$reflectionParams->setAccessible(true);

$params             = $reflectionParams->getValue($connection);
$params['dbname']   = $database; // read from the customer specific .env
$params['user']     = $username; // read from the customer specific .env
$params['password'] = $password; // read from the customer specific .env

$reflectionParams->setValue($connection, $params);
$reflectionParams->setAccessible(false);

$this->entityManager = $this->entityManager->create(
    $this->entityManager->getConnection(),
    $this->entityManager->getConfiguration()
);

This works fine! 这样很好!

The problem is the security context (?) - we are using FosUserBundle which is not able to authorize the users. 问题是安全上下文(?)-我们使用的是FosUserBundle,它无法授权用户。 I'm guessing the code above is not enough to affect security context. 我猜上面的代码不足以影响安全上下文。

What would be the proper way to achieve the goal of having dynamic database connection + user authorization using standard FosUserBundle? 使用标准的FosUserBundle实现动态数据库连接+用户授权的目标的正确方法是什么?

The problem was not related to security context at all. 该问题根本与安全上下文无关。 The issue (silly) was that my kernel request listener had the default priority (0) which made the whole customer config loading and connection setting after the login listener takes place. 问题(傻)是我的内核请求侦听器具有默认优先级(0),这使登录侦听器发生后整个客户配置加载和连接设置。

Setting it to 512 (should be enough) to kick-in before SessionListener 将其设置为512(应该足够)以在SessionListener之前启动

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM