问题
It's possible to load different parameters.yml on symfony? I have a SaaS multitenant APP and I wish load differents parameters.yml (with config DB) base on each tenant in order to dispatch the user to the correct DB on login action.
Thanks so much!
EDIT: SOLVED!
I solved it arranging the different tenants configurations in folders like:
app
---config
------tenantA
---------config.yml
---------config_dev.yml
---------config_prod.yml
---------parameters.yml
------tenantB
---------config.yml
---------config_dev.yml
---------config_prod.yml
---------parameters.yml
------tenantC
---------config.yml
---------config_dev.yml
---------config_prod.yml
---------parameters.yml
....
And, modifying the loader of kernelApp.php:
$loader->load($this->getRootDir().'/config/TENANT/config_'.$this->getEnvironment().'.yml');
I don't know if this is a good practice but it works fine!
回答1:
You have several possibilities here.
If tenant's number is a constant or close to it (new tenants are added very rarely) you can simply setup several connections as described here. After that you can get necessary EntityManager
instance by calling
$em = $this->get('doctrine')->getManager($dynamicValue);
Downside of this approach is that you must modify your config.yml
each time you need create/update/delete a tenant.
But if you want more flexible approach you can implement your own class for managing database connections:
<?php
namespace AppBundle\Service;
use AppBundle\Entity\Database;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\DriverManager;
/**
* Class ConnectionManager
* @package AppBundle\Service
*/
class ConnectionManager
{
/**
* @var Connection[]
*/
protected $connections = [];
/**
* @param Database $database
* @return Connection
* @throws DBALException
*/
public function getConnection(Database $database)
{
$params = [
'dbname' => $database->getName(),
'user' => $database->getUser(),
'password' => $database->getPassword(),
'host' => $database->getHost(),
'driver' => 'pdo_mysql',
];
$key = $this->getKey($params);
if (isset($this->connections[$key])) {
return $this->connections[$key];
}
$conn = DriverManager::getConnection($params);
$this->connections[$key] = $conn;
return $conn;
}
/**
* @param array $params
* @return string
*/
protected function getKey($params)
{
sort($params);
return md5(implode('.', $params));
}
}
来源:https://stackoverflow.com/questions/41672130/symfony-its-possible-load-different-parameters-yml