Setting Up Yii2 Db Connection

Hi there,

I’m trying to set up a Yii 2.0 basic application and the problem that I’m facing is to configure the database connection.

I have not found any hints about database connection in the config directory files (web.php, web-test.php, params.php and console.php).

I’ve found though some info in codeception.yml, but I’m not sure that this file is intended for db connection related purposes.

In Yii 1.x, following the recipes of Jacmoe (if I remember well), I was always adding a line


'db'=>require(dirname(__FILE__) . '/dev_db.php'),

into protected/config/main.php, which recalled dev_db.php that contained


return array(

	'class'=>'CDbConnection',

	'connectionString' => 'mysql:host=localhost;dbname=dbname',

	'emulatePrepare' => true,

	'username' => 'user_dev',

	'password' => '...',

        ...

	);

Similar approach I used for the test environment and for the console.

I’m wondering what is the way to set up the database connection for different environments in Yii 2.0?

Here’s my config for local env:


<?php


$config = require(__DIR__ . '/web.php');


$config['components']['cache'] = array(

    'class' => 'yii\caching\ApcCache',

);


$config['components']['db'] = array(

    'class' => 'yii\db\Connection',

    'dsn' => 'mysql:host=localhost;dbname=...',

    'username' => 'root',

    'password' => '...',

    'charset' => 'utf8',

    // 'enableSchemaCache' => true,

    // 'schemaCacheDuration' => 3600,

);


return $config;

So in index.php (actually, mine is called index_local.php and local htaccess is pointing to it) I just load local config

$config = require(DIR . ‘/../config/web-local.php’);

and that’s it.

So, if I get you right, somehow a key ‘db’ should be added to the array $config[‘components’] in config/web.php?

or to some other config, like web-local.php and web-remote.php. It’s up to you.

Got it, thanks a lot!

Just to test if db connection can now be used, I’ve just tried to make a migration typing


yii migrate create create_user_table

and got the message that folder @app/migrations does not exist. So I created it manually (I’ve got some doubts whether it is the correct way). Then, executing again the above command I got a message that I should specify ID of db connection. I don’t know whether I’m on the right way.

I suppose migrations use console.php config, not web.php

Thanks a lot! It works!