開發中可能會遇到一些這樣的問題,比如本地一個數據庫,線上一個數據庫,測試環境一個數據庫,協同辦公一個數據庫,有時候需要進行不斷切換數據庫,這裏操作是在config文件夾下快速更改db.php的內容;
首先yii2中db.php文件的內容是:
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=yii2basic',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
// Schema cache options (for production environment)
//'enableSchemaCache' => true,
//'schemaCacheDuration' => 60,
//'schemaCache' => 'cache',
];
這裏我們在控制檯命令的commands文件夾中創建一個ChangeDbController.php文件夾,進行切庫命令的編寫
/**
* @author: BGSN
*/
public function actionGetDb()
{
$DbDir = __DIR__ . '/../config/db.php';
if (is_file($DbDir)) {
$DbContent = require_once $DbDir;
//假設有庫1:127.0.0.1 dbname=yii2basic username = root ;password:root
// 庫2:127.0.0.2 dbname=yii2basic username = root ;password:root
// 庫3:127.0.0.3 dbname=yii2basic username = root ;password:root
// 庫4:127.0.0.4 dbname=yii2basic username = root ;password:root
$message = '當前庫爲:';
$nowTable = '';
if (false !== strpos($DbContent['dsn'],'127.0.0.1' )) {
$nowTable= '127.0.0.1';
} else if (false !== strpos( $DbContent['dsn'],'127.0.0.2')) {
$nowTable= '127.0.0.2';
} else if (false !== strpos( $DbContent['dsn'],'127.0.0.3')) {
$nowTable= '127.0.0.3';
} else if (false !== strpos($DbContent['dsn'],'127.0.0.4')) {
$nowTable= '127.0.0.4';
}
$message .= $nowTable;
$DbReturn = [];
$this->showMessage($message,$DbReturn);
if (!$DbReturn) {
echo '謝謝操作'."\n";
exit();
}
$confText = "<?php
return [
'class' => 'yii\db\Connection',
'dsn' => '".$DbReturn['table']."',
'username' => '".$DbReturn['user']."',
'password' => '".$DbReturn['password']."',
'charset' => 'utf8',
];";
if (file_put_contents($DbDir,$confText)) {
echo '切換成功:'.$DbReturn['table']."\n";
} else {
echo '切換失敗:'.$nowTable."\n";
}
} else {
echo '數據庫文件不存在'."\n";
}
}
/**
* @param $message
* @param $return
* @author: BGSN
*/
private function showMessage($message,&$return) {
echo $message.'.請選擇需要切換的庫:
1.127.0.0.1
2.127.0.0.2
3.127.0.0.3
4.127.0.0.4
5.退出
如果按其他按鍵,則繼續顯示該條信息
';
$table = $user = $password = '';
$changeDbNumber = fgets(STDIN);
switch ($changeDbNumber) {
case 1: $table = 'mysql:host=127.0.0.1;dbname=yii2basic';$user = 'root';$password = 'root';break;
case 2: $table = 'mysql:host=127.0.0.2;dbname=yii2basic';$user = 'root';$password = 'root';break;
case 3: $table = 'mysql:host=127.0.0.3;dbname=yii2basic';$user = 'root';$password = 'root';break;
case 4: $table = 'mysql:host=127.0.0.4;dbname=yii2basic';$user = 'root';$password = 'root';break;
case 5: die('再見!');
default : $this->showMessage($message,$return);
}
if (!$return) {
$return = ['table' => $table, 'user' => $user,'password' => $password];
}
}
這裏在控制檯輸入命令
php yii change-db/get-db:
cyb basic (develop) $ php yii change-db/get-db
當前庫爲:.請選擇需要切換的庫:
1.127.0.0.1
2.127.0.0.2
3.127.0.0.3
4.127.0.0.4
5.退出
如果按其他按鍵,則繼續顯示該條信息
這裏選擇要切換的庫此時就可以進行快速切庫操作