Multi Tenant Multiple Database Setup [closed]

2019-04-17 12:52发布

We're setting up a multi tenant website using Yii2. We want to allow each user to have it's own database while using the same system. We'll also have a system database that holds the users information and information like invoicing.

Here are some of our questions.

  1. How do we make the second database connection (db2) dynamic, based on information stored in the first database connection (db)?
  2. How do we setup migrations to be applied to all tenant databases (db2) while they are dynamic?
  3. How would we target one dynamic database on initial migration?

There are a few links that have helped but haven't answered all our questions.

Multiple database connections and Yii 2.0

http://www.yiiframework.com/doc-2.0/guide-db-migrations.html

1条回答
你好瞎i
2楼-- · 2019-04-17 13:16

1) It all depends on how you set it up. How will you remember what user has to use what DB? You can always do something like

    'components' => [
        'db1' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=db1name', //maybe other dbms such as psql,...
            'username' => 'db1username',
            'password' => 'db1password',
        ],
        'db2' => function() use ($whatever, $variables, $you, $need) {
            return [
               'class' => 'yii\db\Connection',
               'dsn' => 'mysql:host=localhost;dbname=' . GETTHEDATABASEINAWAY, 
               'username' => GETTHEUSERINAWAY,
               'password' => GETTHEPASSINAWAY,
            ],
        }
    ],

];

More on anonymous functions http://php.net/manual/en/functions.anonymous.php

2) You probably have a list of databases someplace. Create your own migrate controller that extends the main one and you can call it to migrate instead of the the normal yii 2 controller. in console you can create migrationController.php that extends the the Yii2 one, instead of calling php yii migrate/up you will call php yii migration/up.

You can also trick the system to use your own MigrateControllor so you can still use php yii migrate/up , try using the URL rules to do this. I saw a guy doing it another way but I cannot find the location.

3) if you create your own migration controller (see number 2) then just add parameters to the migration command. Right now it can receive parameters like --migration-path and --db , add your own parameter to do what you need.

查看更多
登录 后发表回答