===== MySQLレプリケーション環境対応 =====
==== 動作概要 ====
通常はスレーブに接続
↓
更新クエリ実行前にマスターに接続
↓
更新クエリ実行
↓
更新クエリ実行後、スレーブに接続を戻す
↓
通常スレーブに接続
==== app/config/database.php ====
class DATABASE_CONFIG {
var $default = array( // as MySQL slave server
'driver' => 'mysql',
'persistent' => false,
'host' => 'スレイブのホスト',
'login' => 'ユーザー名',
'password' => 'パスワード',
'database' => 'DB名',
'encoding' => 'utf8'
);
var $master = array( // as MySQL master server
'driver' => 'mysql',
'persistent' => false,
'host' => 'マスターのホスト',
'login' => 'ユーザー名',
'password' => 'パスワード',
'database' => 'DB名',
'encoding' => 'utf8'
);
}
==== app/app_model.php ====
useDbConfig;
$this->setDataSource('master');
$val = parent::save($data, $validate, $fieldList);
$this->setDataSource($oldDb);
return $val;
}
function updateAll($fields, $conditions = true) {
$oldDb = $this->useDbConfig;
$this->setDataSource('master');
$val = parent::updateAll($fields, $conditions);
$this->setDataSource($oldDb);
return $val;
}
function delete($id = null, $cascade = true) {
$oldDb = $this->useDbConfig;
$this->setDataSource('master');
$val = parent::delete($id, $cascade);
$this->setDataSource($oldDb);
return $val;
}
function deleteAll($conditions, $cascade = true, $callbacks = false) {
$oldDb = $this->useDbConfig;
$this->setDataSource('master');
$val = parent::deleteAll($conditions, $cascade, $callbacks);
$this->setDataSource($oldDb);
return $val;
}
}
==== query べた書きのとき(ORM通さない) ====
$sql = 'upate users ...';
$oldDb = $this->useDbConfig;
$this->setDataSource('master');
if(!$this->query($sql)) {
$this->setDataSource($oldDb);
return false;
}
$this->setDataSource($oldDb);