Search code examples
mysqlyiiyii-componentsyii-events

Connect 2 databases in Yii to workwith testdata and real data at the same time


My site is preparing to go live. As updations are developed on my site, I would like to test the updations in real server without affecting the real data. I need 2 databases(the same database with 2 names) to connect my site at the same time. One for testing myself and other for the real users.

I tried duplicating the config/main to config/main_test and the main index.php to index_test.php. And implemented 2 database connections in config/main.php and config/main_test.php. And connected those files to the index.php and index_test.php and tried to run the site with http://mysite.com/index.php and http://mysite.com/index_test.php. But both urls are working based on the database connection provided in config/main.php.

How can I get use the 2 databases? I dont think keeping 2 copies of the entire site is a good idea. All suggestions are welcome


Solution

  • You can implement it with duplicating your config file main.php to main-test.php and index.php to index-test.php. In the main-test.php file set the new DB connection properties. In index-test.php change the path to configuration and you can also enable the debug. Here is an example of your index-test.php:

    $yii = '/opt/yii/framework/yii.php';
    $config = dirname(__FILE__) . '/protected/config/main-test.php';
    
    defined('YII_DEBUG') or define('YII_DEBUG', true);
    defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL', 3);
    
    require_once($yii);
    Yii::createWebApplication($config)->run();
    

    And don't forget to use the URL with index-test.php in it.