如何像cakepress cms一样在cakephp中动态设置数据库文件?

时间:2014-05-05 13:48:19

标签: cakephp

我想动态设置cakephp数据库文件。 执行此操作后,我想像wordpress一样动态地将用户名,密码,站点名称等插入到相关表中。

由于

2 个答案:

答案 0 :(得分:1)

您可以使用ConnectionManager::create()创建动态数据源连接。举个例子:

ConnectionManager::create('dynamic_connection_name', array(
    'datasource' => 'Database/Mysql',
    'host' => 'localhost',
    //etc
);

然后你可以在任何模型上设置它:

$this->useDbConfig = 'dynamic_connection_name'

请查看文档以供进一步参考: http://api.cakephp.org/2.4/class-ConnectionManager.html#_create

答案 1 :(得分:0)

您可以使用file_put_contents创建文件

$dbConfig = "<?php ".PHP_EOL;
$dbConfig .= "class DATABASE_CONFIG { ".PHP_EOL;
    $dbConfig .= "\t".'public $default = array('.PHP_EOL;
        $dbConfig .= "\t\t'datasource' => 'Database/Mysql',".PHP_EOL;
        $dbConfig .= "\t\t'persistent' => false,".PHP_EOL;
        $dbConfig .= "\t\t'host' => 'localhost',".PHP_EOL;
        $dbConfig .= "\t\t'login' => 'username',".PHP_EOL;
        $dbConfig .= "\t\t'password' => 'password',".PHP_EOL;
        $dbConfig .= "\t\t'database' => 'databasename',".PHP_EOL;
        $dbConfig .= "\t\t'prefix' => '',".PHP_EOL;
        $dbConfig .= "\t\t'encoding' => 'utf8'".PHP_EOL;
    $dbConfig .= "\t ); ".PHP_EOL;
$dbConfig .= "} ".PHP_EOL;

file_put_contents(ROOT.DS.'Config'.DS.'database.php', $dbConfig);