Leonardo Delfino
Leonardo Delfino

Reputation: 1498

PHP Yii: Database connect in runtime

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?

Upvotes: 3

Views: 2851

Answers (3)

Daniel Galvan
Daniel Galvan

Reputation: 46

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

Upvotes: 3

Asgaroth
Asgaroth

Reputation: 4334

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 :)

Upvotes: 0

CreatoR
CreatoR

Reputation: 1652

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

Upvotes: 1

Related Questions