title: Yii Database Failover Fail Over
body: <p>I am currently working on a project for which we have chosen Yii as our new Framework of choice. I am currently trying to figure out the best way to implement some sort of automatic database fail over in Yii. </p>
  
  <p>I am currently trying to over-ride the CDbConnection class - Open function. I am not sure if I am headed in the right direction though.</p>
  
  <p>Basically what I am looking to do is check a DB connection and if it fails connect to another DB. Simple concept I am just not sure where to put it. I know there are better ways to do this by using mysqlnd_ms but it is not setup on the servers we are using yet so have to come up with a way to do this in Yii. Any help is greatly appreciated. -DA </p>
  
  <p>This is what I have so far Thoughts?</p>
  
  <pre><code>class DaDbConnection extends CDbConnection{
  
  public $dbConnectTries = 6;
  public $numDatabases = 3;
  private $_tries =0;
  private $_db = 1;
  
  /*
   * Extends CDbConnection open() method
   * Tries to connect to database connections setup in config/main.php up to 
   * the value of $dbConnectionTries or a connection is successful
   * @throws CException If it can not connect to any DBs
   */
  protected function open()
  {
      try{
          //try to connect to the default DB
          parent::open();
  
      }catch(Exception $e){
          if($this-&gt;_tries &lt; $this-&gt;dbConnectTries){
  
              //If there aren't anymore DBs to try we must start over from the first
              if($this-&gt;_db &gt;= $this-&gt;numDatabases){
                  $tryDb = 'db';
                  $this-&gt;_db = 0;
              }else{
                 $tryDb = 'db'.$this-&gt;_db;
              }
  
              $this-&gt;_db++;
              $this-&gt;_tries++;
  
              $this-&gt;connectionString = Yii::app()-&gt;$tryDb-&gt;connectionString;
              $this-&gt;username = Yii::app()-&gt;$tryDb-&gt;username;
              $this-&gt;password = Yii::app()-&gt;$tryDb-&gt;password;
              $this-&gt;open();
          }else{
              throw new CDbException('Could Not Connect to a DB.');
          }
      }    
  }
  </code></pre>
  
  <p>}</p>