您可以像其他答案一样添加多个数据库连接,例如:db/db_for_module。
您也可以像我一样配置模块(使用 Yii2 高级模板的示例):
// in common/config/main.php
[
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=test_db',
'username' => 'root',
'password' => '123456',
'charset' => 'utf8',
],
'modules' => [
'v1' => [
'class' => \frontend\modules\v1\Module::class,
// Increase the component configuration of the module
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=test_db_for_module',
'username' => 'root',
'password' => '111111',
'charset' => 'utf8',
],
],
],
],
]
v1模块的定义
// in frontend/modules/Module.php
<?php
namespace frontend\modules\v1;
/**
* v1 module definition class.
*/
class Module extends \yii\base\Module
{
/**
* {@inheritdoc}
*/
public $controllerNamespace = 'frontend\modules\v1\controllers';
}
但是,您必须在模块代码中以特殊方式调用 db 组件,例如:
// in frontend/modules/v1/controllers/TestController.php
<?php
namespace frontend\modules\v1\controllers;
/**
* Test Controller
*/
class TestController extends \yii\web\Controller {
public function actionTest()
{
\Yii::$app->modules['v1']->db->createCommand(...); // This db points to the db connection of this module configuration
// or
$this->module->db->createCommand(...) // This db points to the db connection of this module configuration
}
}
这样做的好处:
- 您可以使用相同的名称:db(如果这是您所期望的,尽管它以特殊方式调用)
- 此模块以外的代码看不到有关此数据库的配置。
- 即使您没有此模块的特殊db连接,您仍然可以使用上述方法正确调用默认db连接(也许这不是您所期望的)
- 可以清楚的表明这里使用了特殊的db连接配置
注意:这只是一种覆盖模块中应用程序默认组件的方法,以供参考。这个方法我没有实践过,但是我测试过这个是可行的。