I am using PostgreSQL and the default database schema in my Yii2 application.
I created a new schema called laboratory and I need to define it in the common/config/main-local.php file.
This is my current main-local.php file:
<?php
return [
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'pgsql:host=localhost;dbname=travel',
'username' => 'aaaa',
'password' => 'bbbb',
'charset' => 'utf8',
],
],
];
How can I add the laboratory schema in this file? I need both schemas.
Is Yii2 supporting multiples schemas?
You can configure more than one in components
return [
'components' => [
'db1' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=testdb1',
'username' => 'demo1',
'password' => 'demo1',
],
'db2' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=testdb2',
'username' => 'demo2',
'password' => 'demo2',
],
],
];
and you can refer to each one using
\Yii::$app->db1;
or
\Yii::$app->db2;
http://www.yiiframework.com/doc-2.0/guide-db-active-record.html
http://www.yiiframework.com/doc-2.0/guide-start-databases.html
for postgresql you could try
return [
'components' => [
'db1' => [
'class' => 'yii\db\Connection',
'dsn' => 'pgsql:host=localhost;dbname=testdb1',
'username' => 'demo1',
'password' => 'demo1',
'schemaMap' => [
'pgsql'=> [
'class'=>'yii\db\pgsql\Schema',
'defaultSchema' => 'your_schema1' //specify your schema here
]
],
],
'db2' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=testdb2',
'username' => 'demo2',
'password' => 'demo2',
'schemaMap' => [
'pgsql'=> [
'class'=>'yii\db\pgsql\Schema',
'defaultSchema' => 'your_schema2' //specify your schema here
]
],
],
],
];
It wasn't necessary to change it:
<?php
return [
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'pgsql:host=localhost;dbname=travel',
'username' => 'aaaa',
'password' => 'bbbb',
'charset' => 'utf8',
],
],
];
Then Gii code generator recognizes the laboratory schema (but autocomplete for Table Name doesn't work).
Related
I keep getting this error when I'm trying to open Album application from Laminas MVC tutorial. I use multicontainer configuration in Docker which consists of linked containers. These are laminas-mvc-tutorial container and mysql database container. PDO mysql is enabled but I think it is something with my Adapter configuration issues.
Here is global.php config array:
use Laminas\Db\Adapter;
return [
'service_manager' => [
'abstract_factories' => [
Adapter\AdapterAbstractServiceFactory::class
],
'factories' => [
Adapter\AdapterInterface::class => Adapter\AdapterServiceFactory::class,
],
'aliases' => [
Adapter\Adapter::class => Adapter\AdapterInterface::class
]
],
'db' => [
'driver' => 'Pdo',
'adapters' => [
mysqlAdapter::class => [
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=Laminas;host=localhost;charset=utf8',
'username' => 'root',
'port' => '3306',
'password' => 'pass1234',
'driver_options' => [
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
],
],
],
],
];
As far as I am aware. All of this:
'abstract_factories' => [
Adapter\AdapterAbstractServiceFactory::class
],
'factories' => [
Adapter\AdapterInterface::class => Adapter\AdapterServiceFactory::class,
],
'aliases' => [
Adapter\Adapter::class => Adapter\AdapterInterface::class
]
Is not needed. If you are following the docs why are you not in development mode instead of production? Since in development mode this should be read from the local.php file instead of global.php?
'db' => [
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=your_dbname;host=localhost;charset=utf8',
'username' => 'your_username',
'password' => 'your_password',
],
Which is literally the only thing needed to connect to MySQL for laminas/laminas-db
The error you get:
'Laminas\Db\Adapter\Laminas\Db\Adapter\AdapterInterface' not found
I think there is a namespace issue.
Try to use only:
use Laminas\Db;
insted of the one you're currently using.
I am new to Yii2 and need to set up an existing project. I am at the stage where I would like to migrate tables to the database using the console. I have a database connection in Yii, everything in config is specified correctly. However, I get an error in the console when I try to migrate the tables:
Exception 'yiibaseInvalidConfigException' with message 'Failed to instantiate component or class "db".'
I have already searched Google and have not found a solution to this problem.
Here some code:
config/console.php
<?php
use kartik\mpdf\Pdf;
Yii::setAlias('#webdir', realpath(dirname(__FILE__) . '/../../'));
$params = require(__DIR__ . '/params.php');
$db = require(__DIR__ . '/db.php');
$config = [
'id' => 'easyads-console',
'basePath' => dirname(__DIR__),
'aliases' => [
'#assets' => realpath('../assets'),
'#webroot' => realpath('../'),
],
'bootstrap' => [
'log',
'app\yii\base\Settings',
],
'on beforeRequest' => ['\app\init\Application', 'consoleBeforeRequest'],
'controllerNamespace' => 'app\commands',
'modules' => [
'admin' => [
'class' => 'app\modules\admin\Module',
'defaultRoute' => 'admin',
],
],
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
'options' => [
'class' => '\twisted1919\options\Options'
],
'pdf' => [
'mode' => Pdf::MODE_UTF8,
'class' => Pdf::classname(),
'format' => Pdf::FORMAT_A4,
'orientation' => Pdf::ORIENT_PORTRAIT,
'destination' => Pdf::DEST_BROWSER,
],
'urlManager' => [
'enablePrettyUrl' => true,
'rules' => [
[
'pattern' => 'listing/index/<slug:[a-z0-9_\-]+>',
'route' => 'listing/index',
]
]
],
'generateInvoicePdf' => [
'class' => 'app\components\GenerateInvoicePdfComponent',
],
'sendInvoice' => [
'class' => 'app\components\SendInvoiceComponent',
],
'mailer' => [
'class' => 'app\yii\swiftmailer\Mailer',
],
'consoleRunner' => [
'class' => 'vova07\console\ConsoleRunner',
'file' => '#app/console.php'
],
'mailQueue' => [
'class' => 'app\components\mail\queue\MailQueueComponent',
],
'twigTemplate' => [
'class' => 'app\components\mail\template\MailTemplateComponent',
],
'mailSystem' => [
'class' => 'app\components\mail\MailSystemComponent',
],
'migration' => [
'class' => 'twisted1919\helpers\Migration',
],
'mutex' => [
'class' => 'yii\mutex\FileMutex',
],
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
}
if (is_file($file = __DIR__ . "/console-local.php")) {
$config = \yii\helpers\ArrayHelper::merge($config, require $file);
}
return $config;
config/db.php
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=database;port=3306;dbname=db',
'username' => 'root',
'password' => 'root',
'charset' => 'utf8',
'tablePrefix'=> 'ea_',
'on afterOpen' => function($event) {
$event->sender->createCommand('SET time_zone="+00:00"')->execute();
$event->sender->createCommand('SET NAMES utf8')->execute();
$event->sender->createCommand('SET SQL_MODE=""')->execute();
},
];
I am having troubles with the Mailer after upgrading from CakePHP 3 to 4.
This is the relevant part my configuration:
<?php
return [
'EmailTransport' => [
'default' => [
'className' => 'Mail',
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => 'user',
'password' => 'password',
'client' => null,
'tls' => null,
'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
],
'cronjob' => [
'className' => 'Mail',
],
'accounts' => [
'className' => 'Mail',
],
],
'Email' => [
'default' => [
'transport' => 'default',
'from' => 'you#localhost',
],
'cronjob' => [
'transport' => 'cronjob',
'from' => 'cronjob#foobar.com',
],
'accounts' => [
'transport' => 'accounts',
'from' => 'accounts#foobar.com',
],
],
];
This is the snippet that's causing the error:
private function sendActivationEmail(User $user)
{
$url = Router::url([
'prefix' => 'Admin',
'plugin' => 'UserManager',
'controller' => 'Users',
'action' => 'activate',
$user->username,
$user->activation_key,
], true);
debug(Configure::read('EmailTransport'));
debug(Configure::read('Email'));
$mailer = new Mailer('accounts');
$mailer->setFrom(['accounts#foobar.com' => 'Foobar Website Manager'])
->setTo($user->email, $user->fullName)
->setSubject('Please activate your account')
->setEmailFormat('html')
->setViewVars(compact('url', 'user'))
->viewBuilder()
->setTemplate('UserManager.register');
return $mailer->deliver();
}
The error is Unknown email configuration "accounts"., thrown in
The output of the two debug functions is the following:
/vendor/plugins/usermanager/src/Model/Table/UsersTable.php (line 72)
[
'default' => [
'className' => 'Mail'
],
'cronjob' => [
'className' => 'Mail'
],
'accounts' => [
'className' => 'Mail'
]
]
/vendor/plugins/usermanager/src/Model/Table/UsersTable.php (line 73)
[
'default' => [
'transport' => 'default',
'from' => 'something#foobar.com'
],
'cronjob' => [
'transport' => 'cronjob',
'from' => 'cronjob#foobar.com'
],
'accounts' => [
'transport' => 'accounts',
'from' => 'accounts#foobar.com'
]
]
So it seems like the accounts key is present in the mail configuration, then why am I getting this error?
Make sure that you have upgraded your bootstrap.php accordingly along the way, specifically with regards to how EmailTransport and Email are being consumed, this was introduced with CakePHP 3.7 and 4.1 if I'm not mistaken:
TransportFactory::setConfig(Configure::consume('EmailTransport'));
Mailer::setConfig(Configure::consume('Email'));
https://github.com/cakephp/app/blob/4.2.2/config/bootstrap.php#L163-L164
I want to setup module's database independent from base project and configure it from config/web.php like the following:
'modules' => [
'user' => [
///...
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'pgsql:host=127.0.0.1;port=5432;dbname=klabs',
'username' => 'postgres',
'password' => '',
'charset' => 'utf8',
]
]
]
Is it available to make so? And how to do it, if yes?
First, you need config other database components like that:
...
'components' => [
'db1' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=db1name',
'username' => 'db1username',
'password' => 'db1password',
],
'db2' => [
'class' => 'yii\db\Connection',
'dsn' => 'pgsql:host=localhost;port:5432dbname=db2name',
'username' => 'db2username',
'password' => 'db2password',
],
],
...
And choose db component you defined before in your module config:
'modules' => [
'user' => [
'class' => 'other\to\UserModule',
'layout' => 'main',
'db' => 'db2', // or db1
...
],
],
Hope it helpful.
Goodluck and have fun!
I'm going through Security-Authorization Tutorial to configure authManager using DbManager.
After declaring the below code in web.php
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
'urlManager' => [
'showScriptName' => false,
'enablePrettyUrl' => true
],
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'tYXyeisqgn9Qn_baaI6JRV4a6NY54nrq',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'viewPath' => '#backend/mail',
'useFileTransport' => true,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'localhost',
'username' => 'root',
'password' => '',
'port' => '8080',
'encryption' => 'tls',
],
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => require(__DIR__ . '/db.php'),
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
}
return $config;
And, this code in console.php
<?php
Yii::setAlias('#tests', dirname(__DIR__) . '/tests');
$params = require(__DIR__ . '/params.php');
$db = require(__DIR__ . '/db.php');
return [
'id' => 'basic-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log', 'gii'],
'controllerNamespace' => 'app\commands',
'modules' => [
'gii' => 'yii\gii\Module',
],
'components' => [
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
],
'params' => $params,
];
config/db.php
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=danishYii',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
];
I typed ./yii migrate --migrationPath=vendor/yiisoft/yii2/rbac/migrations
in my terminal. This command i got from Component is not getting loaded -Stack overflow
I got this error in my terminal
Exception 'yii\db\Exception' with message 'SQLSTATE[HY000] [2002]
Can't connect to local MySQL server through socket
'/var/run/mysqld/mysqld.sock' (2)'
I'm very new to Yii. So please don't mind if this is a silly question.
Please help me to rectify this problem.
Check if in your
console/config/main.php
you have a proper configuration for db access like this sample for yii2-app-advanced template
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=your_hostname;dbname=your_dbname',
'username' => 'your_username',
'password' => 'your_password',
'charset' => 'utf8',
'enableSchemaCache' => true,
],
for basic template
be sure you have in basic/console/config.php a reference to db in component secion like this
return [
.......
'components' => [
......
'db' => require(__DIR__ . '/db.php'),
],
......
];
and then in basci/config/db.php a properly db config
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=your_hostname;dbname=your_dbname',
'username' => 'your_username',
'password' => 'your_password',
'charset' => 'utf8',
];