PHP Yii: Database connect in runtime

强颜欢笑 提交于 2019-12-12 14:15:52

问题


I would like to connect to a second database with Yii at runtime. The database name would come from a database table after the user to login.

I saw in a tutorial I should do this:

$db2 = Yii::createComponent(array(
    'class' => 'EMongoClient',
    'server' => 'mongodb://127.0.0.1:27017',
    'db' => $emp['database']
));

Yii::app()->setComponent('db2',$db2);

But in my controler when I access Yii::app()->db2 get the error:

Property "CWebApplication.db2" is not defined

What am I doing wrong?


回答1:


The following works for me:

Yii::app()->mongodb->setActive(false);
Yii::app()->mongodb->setServer('mongodb://localhost:27017');
Yii::app()->mongodb->setDb('db1');
Yii::app()->mongodb->setActive(true);



回答2:


UPDATED: Try, instead instance, pass configurations:

Yii::app()->setComponent( 'db2', array(
                                      'class' => 'EMongoClient',
                                      'server' => 'mongodb://127.0.0.1:27017',
                                      'db' => $emp['database']
                                  )
);

Or, you may create special index on params in configurations, such as:

  ...
  'params' => array(
         'db2' => null,
     ),

And the use Yii::app()->params['db2'] = $db2




回答3:


From this comment:

My problem is not with the creation of the component. Soon after creating if I access Yii::app()->db2 its works, but when I try to access via another model or controller I get the error

I think you are setting this component only once somewhere, and then making subsequent requests to different controllers.

You need to put the code, somewhere it is being called EVERYTIME, on every Request. thats how PHP works, there is no "global application state"

by default Yii comes with protected/components/controller.php has base controller for the rest of the app.

my suggestion would be to put your code on the init() method of that controller, so that it always gets called.

You mentioned the database name comes from a table once the user logs in, so you need to save that value in the session, in other to be able to access it in the other requests:

<?php

// After login in
Yii::app()->user->setState('db_name', $db_name);

// in protected/components/controller.php
public function init()
{
    if (!Yii::app()->user->isGuest) {
        $db2 = Yii::createComponent(array(
            'class' => 'EMongoClient',
            'server' => 'mongodb://127.0.0.1:27017',
            'db' => Yii::app()->user->getState('db_name')
        ));

        Yii::app()->setComponent('db2',$db2);
    }
}

Hope it helps, I am assuming many things here :)



来源:https://stackoverflow.com/questions/19428597/php-yii-database-connect-in-runtime

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