cakephp控制台应用程序中的多个数据库

时间:2014-12-19 09:12:44

标签: php mysql schema database-migration cakephp-2.3

以下是我的蛋糕控制台代码,用于生成数据库架构。我必须管理多个数据库模式迁移。当我调用generateDb函数时,它创建了一个主模式,之后我将数据库连接切换到客户端数据库,但客户端模式没有生成。它再次生成主模式。

class HelloShell extends AppShell {
    public $uses = array('ClientDbdetail');
    public function generateDb() {
        $runCommand = shell_exec(APP.'Console/cake schema generate -f master');
        if ($runCommand) {
            $sessionArray = $this->ClientDbdetail->find('first', array('recursive' => -1));
            $this->__switchDb($sessionArray['ClientDbdetail']);
            shell_exec(APP.'Console/cake schema generate -f client');
            $this->out('Schema generated');
        } else {
            $this->out('Schema not generated');
        }
    }

    private function __switchDb(array $userDetail) {
        $username = 'default';
        $settings = array(
            'datasource' => 'Database/Mysql',
            'persistent' => false,
            'host' => 'localhost',
            'port' => 3306,
            'login' => $userDetail['user_dbuser'],
            'password' => $userDetail['user_dbpwd'],
            'database' => $userDetail['user_dbname'],
            'prefix' => ''
        );
        ConnectionManager::drop($username);
        ConnectionManager::create($username, $settings);
        ConnectionManager::getDataSource($username);
    }
}

1 个答案:

答案 0 :(得分:1)

从CakePHP书中有一个例子。

public $connection = 'default';

public function before($event = array()) {
    $db = ConnectionManager::getDataSource($this->connection);
    $db->cacheSources = false;
    return true;
}

之后:

public function before($event = array()) {
    $articles = ClassRegistry::init('Articles', array(
        'ds' => $this->connection
    ));
    // Do things with articles.
}

请参阅:http://book.cakephp.org/2.0/en/console-and-shells/schema-management-and-migrations.html