Symfony: It's possible load different parameters.yml?

我只是一个虾纸丫 提交于 2019-12-24 08:02:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!