如何从Cake Shell读取数据库配置设置?

the*_*her 16 cakephp

我想编写一个蛋糕shell,使用mysqldump对我的数据库进行夜间备份.我可以将它作为一个shell脚本,但是如果我可以将它塞进一个CakePHP shell中,那么我将获得它在开发和实时服务器上工作的额外好处,如果我可以让它自动读取我的数据库配置设置.我会把蛋糕壳做成cron,并且知道我经常备份我的数据库时会有一些安心.

在我的shell中,我正在尝试构建一个以"mysqldump --user ="开头的字符串,我想从app/config/database.php获取用户名.我怎样才能获得database.php中的数据?

Mor*_*eal 29

在蛋糕2.1中,格式已更改为:

App::uses('ConnectionManager', 'Model');
$dataSource = ConnectionManager::getDataSource('default');
$username = $dataSource->config['login'];
Run Code Online (Sandbox Code Playgroud)


dho*_*tet 11

以下代码片段可以解决这个问题:

App::import('Core', 'ConnectionManager');
$dataSource = ConnectionManager::getDataSource('default');
$username = $dataSource->config['login'];
Run Code Online (Sandbox Code Playgroud)


Sum*_*ker 3

格式 CakePHP 3.x已更改为 -

use Cake\Datasource\ConnectionManager;
$source = ConnectionManager::get('default');

debug($source); #Debugging the result
Run Code Online (Sandbox Code Playgroud)

结果 :

object(Cake\Database\Connection) {
  'config' => [
    'password' => '*****',
    'username' => '*****',
    'host' => '*****',
    'database' => '*****',
    'driver' => 'Cake\Database\Driver\Mysql',
    'persistent' => false,
    'encoding' => 'utf8',
    'timezone' => 'UTC',
    'cacheMetadata' => true,
    'quoteIdentifiers' => false,
    'log' => false,
    'url' => null,
    'name' => 'remote'
  ],
  'driver' => object(Cake\Database\Driver\Mysql) {
    'connected' => false
  },
  'transactionLevel' => (int) 0,
  'transactionStarted' => false,
  'useSavePoints' => false,
  'logQueries' => false,
  'logger' => null
}
Run Code Online (Sandbox Code Playgroud)

得到结果:

debug($source->config()); #Accessing the result
Run Code Online (Sandbox Code Playgroud)

结果 :

[
  'driver' => 'Cake\Database\Driver\Mysql',
  'persistent' => false,
  'host' => 'localhost',
  'username' => 'username',
  'password' => 'password',
  'database' => 'database',
  'encoding' => 'utf8',
  'timezone' => 'UTC',
  'cacheMetadata' => true,
  'quoteIdentifiers' => false,
  'log' => false,
  'url' => null,
  'name' => 'remote'
]
Run Code Online (Sandbox Code Playgroud)