Using Symfony 4, we are building a multi-customer application where each customer has a dedicated database. 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.
We have 2x database connection & 2x entity managers - common
& customer
. customer
entity manager is the default one in fact. Obviously, customer
entity manager does not have the correct connection params at first.
We load the extra .env file accordingly (e.g. based on the domain) on kernel request and set the customer
connection and entity manager accordingly:
$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. 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?