サブノート

技術的なトピックが中心の備忘録

[PHP][CakePHP]DB接続先の切り替えを bootstrap.php で行う

DB接続先の切り替えをbootstrap.phpで行うよう編集する。

./app/config/database.php の設定。

<?php
class DATABASE_CONFIG {

  var $test = array(
    'driver' => 'mysql',
      :
      :
  );

  var $product = array(
    'driver' => 'mysql',
      :
      :
  );

  /** DBの切り替え **/
  public function __construct() {

    //cf. bootstrap.php
    $connection = Configure::read('database');

    if(!empty($this->{$connection})) {
      $this->default = $this->{$connection};
    }
  }

}
?>

./app/config/bootstrap.php の設定。

<?php
//Configure::write('database', 'test');
Configure::write('database', 'product');
?>