私は、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 コンポーネントをプロパティに配置する人がいます。なぜ彼らはそれをするのですか?この方法では、データベース接続が必要以上に何度も行われるのではないかと心配しています。