PHP Yii: connecting to a database at runtime

I would like to connect to a second database with Yii at runtime. The database name will appear from the database table after the user logs in.

In the tutorial, I saw 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 controller, when I access Yii::app()->db2, we get an error:

Property "CWebApplication.db2" not defined

What am I doing wrong?

+3
source share
3 answers

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);
+3
source

UPDATED: try passing configurations instead of instance:

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

Or you can create a special index in paramsthe configurations, for example:

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

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

+1

:

. , Yii:: app() → db2, , ,

, -, .

, - EVERYTIME, . PHP, " "

Yii protected/components/controller.php .

, init() , .

, , , - :

<?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);
    }
}

, , :)

0

All Articles