title: Dynamically change database connection Yii
body: <p>I'm working on a project where multiple websites will be run from one Yii installation. Each website will have his own database though, so the database connection must be dynamically.</p>
  
  <p>What i did, i created a BeginRequestBehavior which will be launched 'onBeginRequest'. Here i will check which url has been called and determine the matching database (not in my code yet) and create (or overwrite) the 'db' component.</p>
  
  <pre><code>&lt;?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-&gt;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' =&gt; 'CDbConnection',
              'connectionString' =&gt; 'mysql:host=localhost;dbname=test',
              'emulatePrepare' =&gt; true,
              'username' =&gt; 'secret',
              'password' =&gt; 'verysecret',
              'charset' =&gt; 'utf8',
              'enableProfiling' =&gt; true,
              'enableParamLogging' =&gt; true
          ));
  
          Yii::app()-&gt;setComponent('db', $db);
  
      }
  }
  </code></pre>
  
  <p>It's working fine, but is this the correct approach? In other approaches i see people creating their own 'MyActiveRecord' (extending CActiveRecord) for their models and putting the db component in a property. Why do they do it? I'm afraid the database connection will be made too many times than necessary this way.</p>