Good day. I want to make some databases under yii2 . In fact, if, say, two databases are used, then two bases are written in the components. But my number of databases will grow. Actually you need to make a dynamic connection component. Suppose I have the name of the database to which I want to connect ("13"), and I need to dynamically process the connection component so that it transforms and substitutes the user's id on the fly. How?
|
1 answer
Your application object, the one that is derived from yii\base\Application , has an ancestor in the inheritance chain of the class yii\di\ServiceLocator , which is responsible for working with the application components.
At the moment when you already know the name of the database to which you want to connect, you can create its component and make it accessible to the entire application through the set() method inherited from great-grandfather:
Yii::$app->set('dynamicDbConnection', [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=127.0.0.1;dbname=demo', // здесь прописываете доступы к нужной Вам базе 'username' => 'root', 'password' => '', 'charset' => 'utf8', ]); http://www.yiiframework.com/doc-2.0/yii-di-servicelocator.html#set%28%29-detail
|