3

私は、1 つの Yii インストールから複数の Web サイトを実行するプロジェクトに取り組んでいます。ただし、各 Web サイトには独自のデータベースがあるため、データベース接続は動的でなければなりません。

私がしたことは、「onBeginRequest」で起動されるBeginRequestBehaviorを作成しました。ここでは、どの URL が呼び出されたかを確認し、一致するデータベース (まだ私のコードにはありません) を特定し、「db」コンポーネントを作成 (または上書き) します。

<?php
class BeginRequestBehavior extends CBehavior
{

    /**
     * Attaches the behavior object to the component.
     * @param CComponent the component that this behavior is to be attached to
     * @return void
     */

    public function attach($owner)
    {

        $owner->attachEventHandler('onBeginRequest', array($this, 'switchDatabase'));

    }

    /**
     * Change database based on current url, each website has his own database.
     * Config component 'db' is overwritten with this value
     * @param $event event that is called
     * @return void
     */

    public function switchDatabase($event)
    {
        // Here some logic to check which url has been called..

        $db = Yii::createComponent(array(
            'class' => 'CDbConnection',
            'connectionString' => 'mysql:host=localhost;dbname=test',
            'emulatePrepare' => true,
            'username' => 'secret',
            'password' => 'verysecret',
            'charset' => 'utf8',
            'enableProfiling' => true,
            'enableParamLogging' => true
        ));

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

    }
}

うまく機能していますが、これは正しいアプローチですか?他のアプローチでは、モデル用に独自の「MyActiveRecord」(CActiveRecord を拡張) を作成し、db コンポーネントをプロパティに配置する人がいます。なぜ彼らはそれをするのですか?この方法では、データベース接続が必要以上に何度も行われるのではないかと心配しています。

4

2 に答える 2

4

彼女の DB 接続を定義するためにモデル関数を使用します。

public static $conection; // Model attribute

public function getDbConnection(){

    if(self::$conection!==null)
        return self::$conection;

    else{
        self::$conection = Yii::app()->db2; // main.php - DB config name

        if(self::$conection instanceof CDbConnection){
            self::$conection->setActive(true);
            return self::$conection;
        }
        else
            throw new CDbException(Yii::t('yii',"Active Record requires a '$conection' CDbConnection application component."));
    }
}

main.php :

 'db'=>array( 
    'connectionString' => 'mysql:host=192.168.1.*;dbname=database1',
    'emulatePrepare' => true,
    'username' => 'root',
    'password' => 'password',
    'charset' => 'utf8',
    'enableProfiling'=>true,
    'enableParamLogging' => true,
),
'db2'=>array(
    'class'=>'CDbConnection',
    'connectionString' => 'mysql:host=192.168.1.*;dbname=database2',
    'emulatePrepare' => true,
    'username' => 'root',
    'password' => 'password',
    'charset' => 'utf8',
),
于 2013-11-05T07:13:28.313 に答える
0

yii を使用する場合に複数の db 接続を使用するためのよりクールな方法:

つまり、ユーザー プロファイルと db 接続を格納するために 1 つのメイン db が必要です。

他のスレーブ データベースについては、単一の設定が必要です。必要に応じてデータベース接続を切り替えます。たとえば、ユーザーIDを使用して切り替えます。

私は gii を使用してスレーブ db テーブルのモデルを生成しました。すべてのスレーブ db は同じテーブル構造を持っていると思います。そのモデルの上に、ここに示すように別のクラスを使用します。

    'db' => array(
        'class' => 'PortalDbConnection',
        'connectionString' => 'mysql:host=localhost;dbname=mydb',
        'username' => 'dev',
        'password' => '123456',
        'tablePrefix' => '',
        'emulatePrepare' => true,
        'enableParamLogging' => true,
        'enableProfiling' => true,
        'charset' => 'utf8',
    ),
    'dbx' => array(
        'connectionString' => 'mysql:host=localhost;dbname=mydb1',
        'username' => 'dev',
        'password' => '123456',
        'charset' => 'utf8',
        'tablePrefix' => '',
        'autoConnect' => false,
        'class' => 'CDbConnection', //this may be the reason you get errors! always set this
    ),

そして今、あなたのモデルのphpコード:

<?php

class DomainSlaveM extends Domain {

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public static $server_id = 1;
    public static $slave_db;

public function getDbConnection() {
    self::$slave_db = Yii::app()->dbx;
    if (self::$slave_db instanceof CDbConnection) {
        self::$slave_db->active = false;
        $config = require(Yii::app()->getBasePath() . '/config/location/flavius.php');
        $connectionString = $config['components']['dbx']['connectionString'];
        self::$slave_db->connectionString = sprintf($connectionString, self::$server_id);
        self::$slave_db->setActive(true);
        return self::$slave_db;
    }
    else
        throw new CDbException(Yii::t('yii', 'Active Record requires a "db" CDbConnection application component.'));
}

    }

次のように使用します。

    public function createDomainSlaveM($model) {
//switch the db connection; $server_id gets values, from 1 to N
            DomainSlaveM::$server_id = $model->user_id;
            $model_domain_slave_m = new DomainSlaveM();
            $model_domain_slave_m->attributes = $model->attributes;
            if ($model_domain_slave_m->validate() && $model_domain_slave_m->save()) {
                //ok
            } else {
                //bad
            }
        }
于 2013-11-05T07:17:11.830 に答える