Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 Failing to instantiate component or class "db"

Tags:

migration

yii2

I use a Yii2 console application to run migrations. It's a very basic app, that goes like this (yii.php in the / folder of the project):

<?php

    require __DIR__ . '/vendor/autoload.php';
    require __DIR__ . '/vendor/yiisoft/yii2/Yii.php';
    $config = require __DIR__ . '/config/console.php';

    (new yii\console\Application($config))->run();

?>

So when i run

php yii.php

Everything's fine, but when i run

php yii.php migrate/create create_user_table

I am getting an error message:

Error: Failed to instantiate component or class "db".

My Yii is v2.0.15.1

UPD 19:32 30/12/2018 When I add a db config to a config/console.php like this:

    return [
    'id' => 'school-console',
    'basePath' => dirname(__DIR__),
    'db' => [
              'class' => 'yii\db\Connection',
              'dsn' => 'mysql:host=localhost;dbname=school',
              'username' => 'root',
              'password' => 'Taras1love',
              'charset' => 'utf8',
    ]
];

I get this:

Error: Setting read-only property: yii\console\Application::db
like image 433
tnsaturday Avatar asked Dec 30 '18 13:12

tnsaturday


1 Answers

You are missing the database component configurations for the console application you need to add the following inside the config/console.php file. As you are usign the basic-app for Yii2 you must have a db.php file with the database configurations, you need to include it like below

//this goes on the top of your `console.php` file 
$db = require __DIR__ . '/db.php',

return [
    'id' => 'myapp-console', 
    'basePath' => dirname(__DIR__)
    //add the db component
    'components' => [
        'db' => $db,
    ]
];

Your db.php should be like below inside the config folder, change the values for the username, password and dbname.

<?php

return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=YOUR_DB_NAME',
    'username' => 'DB_USER',
    'password' => 'DB_PASS',
    'charset' => 'utf8',
];

or you can assign it inside the config/console.php if you dont want to create a separate file

return [
    'id' => 'myapp-console', 
    'basePath' => dirname(__DIR__)
    //add the db component
    'components' => [
        'db' => [
           'class' => 'yii\db\Connection',
           'dsn' => 'mysql:host=localhost;dbname=YOUR_DB_NAME',
           'username' => 'DB_USER',
           'password' => 'DB_PASS',
           'charset' => 'utf8',
        ]
    ]
];
like image 145
Muhammad Omer Aslam Avatar answered Nov 10 '22 20:11

Muhammad Omer Aslam