Multi-tenant SaaS built in Yii2

I work in multi-user software (SaaS) built with in an advanced template, but I do not have the desired result about connecting a tenant database.

I am trying to establish a database connection as follows in the configuration file for the interface:

$defaultAdminDB = [
  'class' => 'yii\db\Connection',
  'dsn' => 'pgsql:host=localhost;dbname=untitled',
  'username' => 'postgres',
  'password' => 'myPass',
  'charset' => 'utf8',
];

$config = [
  'components' => [
    'db' => function(){
      if (Yii::$app->session->get('login', false)){
        return [
          'class' => 'yii\db\Connection',
          'dsn' => Yii::$app->session->get('client_connection.dns'),
          'username' => Yii::$app->session->get('client_connection.username'),
          'password' => Yii::$app->session->get('client_connection.password'),
          'charset' => 'utf8',
        ];
      }

      return [
        'class' => 'yii\db\Connection',
        'dsn' => 'pgsql:host=localhost;dbname=untitled',
        'username' => 'postgres',
        'password' => 'myPass',
        'charset' => 'utf8',
      ];
    },
    'dbAdmin' => $defaultAdminDB
  ]
];

Then I have two logins, where the first one asks for a login (tenant identifier), and the next one provides a user and a password. On the first controller, I do the following with:

$account = \frontend\models\AdminAccounts::findOne(['login'=>$this->login]);

if (!$account){
  $this->addError('login', Yii::t('app', 'Account data not found.'));
  return false;
}

$dns = sprintf('pgsql:host=%s;dbname=%s', $account->getAttribute('db_host'), $account->getAttribute('db'));

Yii::$app->session->set('login', $this->login);
Yii::$app->session->set('client_connection.dns', $dns);
Yii::$app->session->set('client_connection.username', $account->getAttribute('db_user'));
Yii::$app->session->set('client_connection.password', $account->getAttribute('db_pass'));

I successfully get the account (tenant) data and save it in the session, but, I think, my mistake is to create an instance yii\db\Connectionfor the model method getDb().

Hope can help me. Yours faithfully!

+4
2

Yii::$app->db = new \yii\db\Connection([
'dsn' => Yii::$app->session->get('client_connection.dsn'),
'username' => Yii::$app->session->get('client_connection.username'),
'password' => Yii::$app->session->get('client_connection.password'),
]);
0

db db, (Yii:: $app- > db- > close()), (Yii:: $app- > db- > Open()).

0

Source: https://habr.com/ru/post/1613996/


All Articles