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',
];
Related
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 want to run yii2 console command, then I test it with run this ./yii
When I run ./yii I got this response
Exception 'yii\base\UnknownPropertyException' with message 'Getting unknown property: yii\console\Application::session'
in /var/www/html/myweb/vendor/yiisoft/yii2/base/Component.php:143
Stack trace:
#0 /var/www/html/myweb/vendor/yiisoft/yii2/di/ServiceLocator.php(73): yii\base\Component->__get('session')
#1 /var/www/html/myweb/vendor/kartik-v/yii2-grid/Module.php(62): yii\di\ServiceLocator->__get('session')
Here is my common/config/params-local.php
return [
'uploadPath' => __DIR__ .'/../../uploads/',
'baseurl' => 'http://localhost/myweb/'
];
Here is my common\config\params.php
<?php
return [
'adminEmail' => 'no-reply#myweb.com',
'supportEmail' => 'no-reply#myweb.com',
'user.passwordResetTokenExpire' => 3600,
];
Here is my console\config\params-local.php
<?php
return [
];
Here is my console\config\params.php
<?php
return [
'adminEmail' => 'no-reply#myweb.com',
];
Here is my common\config\main.php
<?php
return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
],
'modules' => [
'redactor' => [
'class' => 'yii\redactor\RedactorModule',
'uploadDir' => __DIR__ .'/../../uploads/konten',
'uploadUrl' => '/myweb/uploads/konten',
'imageAllowExtensions'=>['jpg','png','gif']
],
'gridview' => [
'class' => '\kartik\grid\Module',
]
],
];
Here is my common\config\main-local.php
<?php
return [
'language' => 'en-US',
'sourceLanguage' => 'id-ID',
'components' => [
'authClientCollection' => [
'class' => 'yii\authclient\Collection',
'clients' => [
'google' => [
'class' => 'yii\authclient\clients\Google',
'clientId' => 'xxxxx-cppd86jm9qfrt77pc684pau01nilf261.apps.googleusercontent.com',
],
'facebook' => [
'class' => 'yii\authclient\clients\Facebook',
'authUrl' => 'https://www.facebook.com/dialog/oauth?display=popup',
'clientId'=> 'xxxxxx16917400',
'clientSecret' => 'xxxxxx8d99ff80ce1f713424',
],
],
],
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'pgsql:host=192.168.0.106;dbname=mydb',
'username' => 'dev',
'password' => 'dev123',
'charset' => 'utf8',
'enableSchemaCache' => false,
'schemaMap' => [
'pgsql'=> [
'class'=>'yii\db\pgsql\Schema',
'defaultSchema' => 'public2' //specify your schema here
]
], // PostgreSQL
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#common/mail',
// 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.
'useFileTransport' => true,
],
'mail' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#backend/mail',
'useFileTransport' => false,//set this property to false to send mails to real email addresses
//comment the following array to send mail using php's mail function
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'iix70.hosting.com',
'username' => 'myuser',
'password' => 'mypass',
'port' => '465',
'encryption' => 'ssl',
],
],
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '../../messages',
'sourceLanguage' => 'id-ID',
'fileMap' => [
'app' => 'app.php',
],
],
],
],
]
];
Looks like something wrong with my script.
Currently i'm using ubuntu.
What should I do next in case to fix that? so it should response with yii command list instead of error.
and what cause these error?
Thanks in advance.
When you add a value to common/config folder files, configurations used in all applications like backend, frontend, console, api and others. So in advanced template, you must just add values which are related to all these applications. Based on documentation common folder is files common to all applications. This picture shows it clearly:
For your problem, as others mentioned, you don't have any session in console, but you added or used this module in common/config/params-local.php and based on introduction of this answer, it will be used in console/config/params-local.php and you get an error :).
Update: Based on your updated question, your common/config/main.php file is:
<?php
return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
],
'modules' => [
'redactor' => [
'class' => 'yii\redactor\RedactorModule',
'uploadDir' => __DIR__ .'/../../uploads/konten',
'uploadUrl' => '/myweb/uploads/konten',
'imageAllowExtensions'=>['jpg','png','gif']
],
'gridview' => [
'class' => '\kartik\grid\Module',
]
],
];
gridviw module, implicitly uses session for saving state of sorting. In other side you added this to config folder of common, so based on previous notes, it also will be used in console application. Console doesn't have session (and I think you don't need a grid view in your console :D) and it causes an error. For solving this problem, move this lines
'modules' => [
'redactor' => [
'class' => 'yii\redactor\RedactorModule',
'uploadDir' => __DIR__ .'/../../uploads/konten',
'uploadUrl' => '/myweb/uploads/konten',
'imageAllowExtensions'=>['jpg','png','gif']
],
'gridview' => [
'class' => '\kartik\grid\Module',
]
],
to main.php of frontend or backend folder (based on your situations and use).
I have a trouble.
I install a yii2-user module by folowing link https://github.com/dektrium/yii2-user/tree/0.9.9
When I trying to register I got a success message, but I not receiving confirmation email.
I used OpenServer
config/web.php
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'language' => 'ru-RU',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'modules' => [
'user' => [
'class' => 'dektrium\user\Module',
'mailer' => [
'sender' => ['name#gmail.com' => 'Vlad'], // or ['no-reply#myhost.com' => 'Sender name']
'welcomeSubject' => 'Welcome subject',
'confirmationSubject' => 'Confirmation subject',
'reconfirmationSubject' => 'Email change subject',
'recoverySubject' => 'Recovery subject',
],
],
],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'QqvFfvH3g3PwMMu_bRRHB4Qz0uPJwiB-',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
// 'user' => [
// 'identityClass' => 'app\models\User',
// 'enableAutoLogin' => true,
// ],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// 'transport' => [
// 'class' => 'Swift_SmtpTransport',
// 'host' => 'smtp.gmail.com',
// 'username' => 'name#gmail.com',
// 'password' => 'mypassword',
// 'port' => '587',
// 'encryption' => 'tls',
// ],
// 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.
// 'useFileTransport' => false,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => require(__DIR__ . '/db.php'),
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
],
'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;
Untill your environment is in dev mode, you will never receive the emails.
You have 3 differents way for read the emails:
the dev bar in bottom, if there is not any redirect after send email, you can open and find it there
in the server, looking for runtime/mail/ folder and there will be the sended emails
deploy enviroment from developer to production
The mailer component should be at the same level as model component.
You can configure it as follows:
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#app/mailer',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.mailtrap.io', // your host, here using fake email server (https://mailtrap.io/). You can use gmail: 'host' => 'smtp.gmail.com'
'username' => 'your host username',
'password' => 'your host password',
'port' => '2525',
'encryption' => 'tls',
],
],
I installed the extension reportico through composer and already web.php configuration file, but when I go into Reportico Admin Page error instead. The solution how ?
enter image description here
scrip web.php
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'K1pkkP_iwACp933A03LotJ3AfRsyIb-D',
],
'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.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => require(__DIR__ . '/db.php'),
/*
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
*/
],
'reportico' => [
'class' => 'reportico\reportico\Module' ,
'controllerMap' => [
'reportico' => 'reportico\reportico\controllers\ReporticoController',
'mode' => 'reportico\reportico\controllers\ModeController',
'ajax' => 'reportico\reportico\controllers\AjaxController',
]
],
'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;
Move reportico to components array:
'components' => [
//...
'reportico' => [
'class' => 'reportico\reportico\Module' ,
'controllerMap' => [
'reportico' => 'reportico\reportico\controllers\ReporticoController',
'mode' => 'reportico\reportico\controllers\ModeController',
'ajax' => 'reportico\reportico\controllers\AjaxController',
]
]
]
I have define a module named `admin' in yii2.
I have registered this module in web.php config file.
But when I try to access this I face with an error.
here is my web.php
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'language'=>'fa_ir',
'bootstrap' => ['log'],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'SiMhYyhP2MZ_BAi321KfDHFk5uleQFa9',
],
'jdate' => [
'class' => 'jDate\DateTime'
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'modules' => [
'admin' => [
'class' => 'app\modules\admin\Module',
],
],
'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.
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'pishevaris#gmail.com',
'password' => 'bhtk1368',
'port' => '587',
'encryption' => 'tls',
],
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'urlManager' => [
'class' => 'yii\web\UrlManager',
// Disable index.php
'showScriptName' => false,
// Disable r= routes
'enablePrettyUrl' => true,
'rules' => array(
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
),
],
'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;
here is my Module class:
<?php
namespace app\modules\admin;
class Module extends \yii\base\Module
{
public $controllerNamespace = 'app\modules\admin\controllers';
public function init()
{
parent::init();
// custom initialization code goes here
}
}
but when I try to access mysite/admin/default/index I face The configuration for the "modules" component must contain a "class" element error
Please define module in out side of component. Like
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'language'=>'fa_ir',
'bootstrap' => ['log'],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'SiMhYyhP2MZ_BAi321KfDHFk5uleQFa9',
],
'jdate' => [
'class' => 'jDate\DateTime'
],
'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.
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'pishevaris#gmail.com',
'password' => 'bhtk1368',
'port' => '587',
'encryption' => 'tls',
],
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'urlManager' => [
'class' => 'yii\web\UrlManager',
// Disable index.php
'showScriptName' => false,
// Disable r= routes
'enablePrettyUrl' => true,
'rules' => array(
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
),
],
'db' => require(__DIR__ . '/db.php'),
],
'modules' => [
'admin' => [
'class' => 'app\modules\admin\Module',
],
],
'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;
Modules are different with Components, and you defined your module as a component by adding this to component array. you should write your module after or before component. like below:
['components'] => [],
['modules'] => [],