Yii Framework Forum: Dynamic Multiple Databases - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Dynamic Multiple Databases database Rate Topic: -----

#1 User is offline   jqvist 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 4
  • Joined: 04-February 13

Posted 09 February 2013 - 10:31 AM

My project is on the basis of multi-tenent SaaS.

I have multiple clients (companies) and each client has multiple users - they all will use the same database layout.

Each client has their own database, so during user authentication, I want to Build a master database that associates the user with a company database for that user.

The structure of each database is identical... only the data is different.

So that we can keep the different database for the different company, that will not going to mix in data in database.

The number of clients (and therefor the number of databases) is unknown when the application is written, so it is not possible to include all the connections in the bootstrap script.

Now, what I want to do is, dynamically alter the DB connection that is in the bootstrap or have the ability to dynamically create a new connection for the user signing in. Is there a simple solution for this in Yii and still use AR , query builder ?

I saw this solution but not working for me http://www.yiiframew...-db-connection/
0

#2 User is offline   jqvist 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 4
  • Joined: 04-February 13

Posted 09 February 2013 - 10:35 AM

This is how my config file looks today for the script running one database, i want to call a master database that controls which database the user belongs to and the app uses in Yii, any idea?

<?php


// Configure for production.
$language = 'en';
$currencyBaseCode = 'USD';
$theme = 'default';
$connectionString = 'mysql:host=localhost;port=3306;dbname=master';
$username = 'root';
$password = 'YOUR PASS';
$memcacheServers = array( // An empty array means memcache is not used.
array(
'host' => '127.0.0.1',
'port' => 11211, // This is the default memcached port.
'weight' => 100,
),
);
$adminEmail = 'EMAIL ADDRESS';
$installed = true; // Set to true by the installation process.
$maintenanceMode = false; // Set to true during upgrade process or other maintenance tasks.
$instanceConfig = array(); //Set any parameters you want to have merged into configuration array.
//@see CustomManagement
$instanceConfig['components']['request']['hostInfo'] = 'website url';
$instanceConfig['components']['request']['scriptUrl'] = '/app/index.php';

$urlManager = array (); // Set any parameters you want to customize url manager.
0

#3 User is offline   seenivasan 

  • Master Member
  • PipPipPipPip
  • Yii
  • Group: Members
  • Posts: 620
  • Joined: 17-June 12
  • Location:Chennai,TamilNadu,India.

Posted 09 February 2013 - 02:20 PM

Dear Friend

I have no idea about Saas.

I am not a professional in web development.

I once succeeded in switching between databases depending on the values stored in sessionin my localhost.

I hope we can apply that in your scenario.

If user has right to have separate database, when he gets logged in we are storing his id as database name.

SiteController.php
public function actionLogin()
        {       
            $model=new LoginForm;
            if(isset($_POST['LoginForm']))
            {
                $model->attributes=$_POST['LoginForm'];

                if($model->validate() && $model->login())  {

                        $user=User::model()->findByAttributes(array('username'=>Yii::app()->user->id));

                        if($user->hasOwnDatabase)
                             Yii::app()->user->setState('database',Yii::app()->user->id);

                        $this->redirect(Yii::app()->user->returnUrl);  }
            }
                
                $this->render('login',array('model'=>$model));
        }


Create an application behavior and attach it to main application.

applicationBehavior.php in components directory
<?php
class applicationBehavior extends CBehavior
{      
    private $_owner;
    public function events() {

                        return  array(
                                'onBeginRequest'=>'assignDb',        
                        );
                             }
        
    public function assignDb()
    {
        $owner=$this->_owner=$this->getOwner();
                
        if(!$owner->user->getIsGuest && $owner->user->hasState('database'))
        {
            $database=Yii::app()->user->getState('database');                
            $owner->db->setActive(FALSE);   

$owner->setComponent('db',new CDbConnection("mysql:host=localhost;dbname=$database",'root','yourpassword'));
                                                   
            $owner->db->setActive(TRUE);
                                
        }
    }
        
}
?>


Attach this behavior instance as a property to main configuration file. Leave the 'db' component intact.

return array(
......................................
.......................................
'behaviors'=>array(
'class'=>'application.components.applicationBehavior',
),
......................................
......................................
'components'=>array(
.........................................
........................................
'db'=>array(
                        'connectionString' => 'mysql:host=localhost;dbname=routine',//routine-default database
                        'emulatePrepare' => true,
                        'username' => 'root',
                        'password' => 'password',
                        'charset' => 'utf8',
                ),
.....................................................
....................................................
),
)


So when user is created, if he has right to have separate database it is stored as a boolean. Then we create a separate database on his name. After successful registration, when he login, he will use his own database on the next immediate request. Otherwise he will work on default database.

I hope this helps you a bit.

Regards.
0

#4 User is offline   jqvist 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 4
  • Joined: 04-February 13

Posted 09 February 2013 - 02:34 PM

It didn't seem to work for me, it is like when i call the "Master" database it doesn't know what to do the master database is only forwarding to the users assigned database... so only have Username, Email, Password and Databasename that it calls in it... any idea? and table name in database is "companylist"
0

#5 User is offline   seenivasan 

  • Master Member
  • PipPipPipPip
  • Yii
  • Group: Members
  • Posts: 620
  • Joined: 17-June 12
  • Location:Chennai,TamilNadu,India.

Posted 09 February 2013 - 02:53 PM

Dear Friend

sorry about that.

The following is my inference.

Every user belongs to a company.

Every company has a separate database.

every user belonging to a particular company will use the database of that company.

Now we have to define relationship between user and company.

every user will have a comany_id.

public function actionLogin()
        {       
            $model=new LoginForm;
            if(isset($_POST['LoginForm']))
            {
                $model->attributes=$_POST['LoginForm'];

                if($model->validate() && $model->login())  {

                        $user=User::model()->findByAttributes(array('username'=>Yii::app()->user->id));

                        if($user->company->hasOwnDatabase)
                             Yii::app()->user->setState('database',Yii::app()->user->company->id); //This way we are grouping users to use database of the company they belong.

                        $this->redirect(Yii::app()->user->returnUrl);  }
            }
                
                $this->render('login',array('model'=>$model));
        }

0

#6 User is offline   jqvist 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 4
  • Joined: 04-February 13

Posted 09 February 2013 - 04:28 PM

Tried no succes... do i need to modify what you send me?
0

#7 User is offline   seenivasan 

  • Master Member
  • PipPipPipPip
  • Yii
  • Group: Members
  • Posts: 620
  • Joined: 17-June 12
  • Location:Chennai,TamilNadu,India.

Posted 09 February 2013 - 04:53 PM

Dear Friend

The code below is very primitive indeed.
public function actionLogin()
        {       
            $model=new LoginForm;
            if(isset($_POST['LoginForm']))
            {
                $model->attributes=$_POST['LoginForm'];

                if($model->validate() && $model->login())  {

                        $user=User::model()->findByAttributes(array('username'=>Yii::app()->user->id));

                        if($user->company->hasOwnDatabase)
                             Yii::app()->user->setState('database',Yii::app()->user->company->id); //This way we are grouping users to use database of the company they belong.

                        $this->redirect(Yii::app()->user->returnUrl);  }
            }
                
                $this->render('login',array('model'=>$model));
        }


Try to infuse your own logic indeed.

The above code assumes the following.

1.company HAS_MANY relation with user..table has a boolean field(hasOwnDatabase).
which grants permission to have a separate database.

2.We also have to ensure that a database exists in the comany name or id beforehand.

regards.
0

#8 User is offline   yiim 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 49
  • Joined: 28-June 12
  • Location:Germany

Posted 11 February 2013 - 10:33 AM

Another solution: connect to a different db depending on the subdomain:

http://www.yiiframew...ultiple-domains
http://www.yiiframew...tabases-in-yii/
http://www.yiiframew...amic-subdomain/
http://www.yiiframew...support-in-yii/
https://www.google.d...ii+multi+tenant
0

#9 User is offline   CTala 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 94
  • Joined: 17-August 11
  • Location:Chile

Posted 06 February 2014 - 12:35 PM

Actually I choose the config file depending on the domain. I will see the last post to check if I can find a better solution.
--
MSc. Cristian Tala Sánchez
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users