Jason George
Jason George

Reputation: 7002

Yii: using a module specific database for access control

I'm trying to set up a separate database for special set of users who will access my site through a Yii module, but I can't quite seem to get the configuration right.

Here are the relevant files my module heirarchy.

/protected/modules/special
/protected/modules/special/SpecialModule.php
/protected/modules/special/models/SpecialActiveRecord.php
/protected/modules/special/models/Account.php
/protected/modules/special/components/UserIdentity.php

Per instructions here, I've updated my main.config to include a module specific database definition.

'modules'=>array(
    'special'=>array(
        'db'=>array(
            'connectionString'=>'mysql:dbname=specialdatabase',
            'username'=>'special',
            'password'=>'special',
        ),
    ),
),

I have also updated my module to support the database definition by adding public $db to SpecialModule.php and I have created a module specific active record that utilizes the database definition.

class SpecialActiveRecord extends CActiveRecord
{
    public function getDbConnection()
    {
        $db = Yii::app()->controller->module->db;
        return Yii::createComponent($db);
    }
}

Where I'm having trouble is in the account model. My primary web application also implements an account model and the stack trace shows that the module is accessing all of my module specific files through user identity (/protected/modules/special/components/UserIdentity.php). The account model that is being used for authorization, however, is referenced at the site level (/protected/models/Account.php).

Any ideas on the proper way to implement module specific authentication using a module specific database?

Upvotes: 1

Views: 1994

Answers (1)

Jason George
Jason George

Reputation: 7002

Based on a forum post on the Yii site (that I can't seem to locate now), I overcame this issue by adding prefixes to my module models--eg. SAccount.php and SActiveRecord.php.

Additionally, I had to make minor modifications to the getDbConnection routine to activate the database and get everything working in Yii 1.0 (this might not be the case for 1.1). Here I modified the code from the CActiveRecord class.

class SActiveRecord extends CActiveRecord
{
    public function getDbConnection()
    {
        if(self::$db!==null)
            return self::$db;
        else
        {
            $db = Yii::app()->controller->module->db;
            self::$db=Yii::createComponent($db);
            if(self::$db instanceof CDbConnection)
            {
                self::$db->setActive(true);
                return self::$db;
            }
            else
                throw new CDbException(Yii::t('yii','Special Active Record requires a "db" CDbConnection application component.'));
        }
    }
}

Upvotes: 3

Related Questions