I want to create a file .env:
FACEBOOK_CLIENT_ID=*****
FACEBOOK_CLIENT_SECRET=*****
and use variable for config
'facebook' => [
'class' => 'yii\authclient\clients\Facebook',
'clientId' => env('FACEBOOK_CLIENT_ID'),
'clientSecret' => env('FACEBOOK_CLIENT_SECRET'),
],
I have found the solution.
I use package vlucas/phpdotenv.
Thank for all
You can archive this by Utilizing the enviroment constants. If you are using Yii2 advanced when you initialize your application as dev or production yii sets a constant YII_ENV as either dev or production in your index.php entry script.
If you are using yii basic you can set it as per your enviroment. For example we want to define config for dev.
We will proceed and edit our /web/index.php to
defined('YII_ENV') or define('YII_ENV', 'dev');
Then in our config file we would have the following
'facebook' => [
'class' => 'dektrium\user\clients\Facebook',
'clientId' => (YII_ENV_DEV ? 'Your key when in developent' : 'Your Key if not in developement'),
'clientSecret' => (YII_ENV_DEV ? 'Your key when in developent' : 'Your Key if not in developement'),
],
Refere to this for more details on Enviroment Constants http://www.yiiframework.com/doc-2.0/guide-concept-configurations.html#environment-constants
There's a package for Yii2 you can use for dotenv
https://github.com/yiithings/yii2-dotenv
Install:
composer require --prefer-dist yiithings/yii2-dotenv "*"
Usage:
Create a .env in project root directory
DB_HOST="localhost"
DB_NAME="yii2basic"
DB_USER="root"
DB_PASS="YourPassword"
config/db.php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host='. env('DB_HOST') .';dbname='. env('DB_NAME'),
'username' => env('DB_USER'),
'password' => env('DB_PASS'),
'charset' => 'utf8',
];
You could use the dotenv package offered by Symfony. https://symfony.com/doc/current/components/dotenv.html
using it in a PHP file.
use Symfony\Component\Dotenv\Dotenv;
$dotenv = new Dotenv();
$dotenv->load(__DIR__.'/.env');
// You can also load several files
$dotenv->load(__DIR__.'/.env', __DIR__.'/.env.dev');
.env file
DB_USER=root
DB_PASS=pass
accessing the variables from the .env file
$dbUser = $_ENV['DB_USER'];
// you can also use ``$_SERVER``
Related
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
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',
]
]
];
I found that I got this problem if I ran yii directly from vendor/bin.
If I went to the console directory and ran it from there using ./yii, I did not get this error and was able to create the migration.
In other words:
cd <project-root>/vendor/bin
yii migrate/create xxx
did not work
But:
cd <project-root>/console
./yii migrate/create xxx
did work
this happened to me because I accidentally renamed my migration and it was not matching the file name
I am creating a module with the following structure:
common
L modules
LL blog
LLL backend
LLL frontend
LLL common
LLL migrations
I found in yii2 documentation a section about "Separated Migrations"
In console/config/main.php I have set:
'migrate-blog' => [
'class' => 'yii\console\controllers\MigrateController',
'migrationNamespaces' => ['app\common\modules\blog\migrations'],
'migrationTable' => 'migration_blog',
'migrationPath' => null,
]
Then I go to console and run following command:
php yii migrate/create app\\common\\modules\\blog\\migrations\\create_table_blog_post
It returns an error:
Error: Namespace 'app\common\modules\blog\migrations' not found in `migrationNamespaces`
am I missing any settings?
Did you add the following info to config of console.php
'controllerMap' => [
// Migrations for the specific project's module
'migrate-module' => [
'class' => 'yii\console\controllers\MigrateController',
'migrationNamespaces' => ['app\module\migrations'],
'migrationTable' => 'migration_module',
'migrationPath' => null,
],
],
I have seen that you have the config in console/config/main.php then the check the yii file is having the following line.
$config = require(__DIR__ . '/console/config/main.php');
After this instead of running
php yii migrate/create app\\common\\modules\\blog\\migrations\\create_table_blog_post
Run the following command
php yii/migrate-blog/create create_table_blog_post
I hope this helps.
I need to install an app written in Yii 2 on my local computer. I installed composer and initiated the app with:
php /path/to/yii-application/init
Now I need to "create a new database and adjust the components['db'] configuration in common/config/main-local.php accordingly."
I have no clue how to do that.
1) Create database on your server.
2) Open common/config/main-local.php
Edit components to:
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=DATABASE_NAME',
'username' => 'DATABASE_USER',
'password' => 'DATABASE_PASSWORD',
'charset' => 'utf8',
],
If using MAMP with mac then edit dsn line to :
'dsn' => 'mysql:unix_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname=DATABASE_NAME'
I am trying to learn Yii 2 from a book (Web application development with Yii2 and PHP). Somewhere along the line it instructs me to install gii and create crud files with it.
When I installed with the following command:
php composer.phar require --prefer-dist "yiisoft/yii2-gii:*"
I have following error:
Invalid Parameter – yii\base\InvalidParamException
The file or directory to be published does not exist: /var/projectsRoot/crmapp/src/vendor/yiisoft/yii2/gii/assets
My bootstrap code:
//Define Yii debug mode
define (YII_DEBUG, true);
//Including composer autoloader
require (__DIR__ . '/../vendor/autoload.php');
//Including Yii framework
require (__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
//debugging for PHP
ini_set('display_errors', true);
//Getting Configuration
$config = require(__DIR__ . '/../config/web.php');
//Include and launch application
(new yii\web\Application($config))->run();
config file:
return [
'id' => 'crmapp',
'basePath' => realpath(__DIR__ . '/../'),
'components' => [
'request' => [
'cookieValidationKey' => 'your secret key here'
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false
],
'db' => require(__DIR__ . '/db.php')
],
'modules' => [
'gii' => [
'class' => 'yii\gii\Module',
'allowedIPs' => ['192.168.33.1']
]
],
'extensions' => [
require (__DIR__ . '/../vendor/yiisoft/extensions.php')
]
];
extensions file:
$vendorDir = dirname(__DIR__);
return array (
'yiisoft/yii2-bootstrap' =>
array (
'name' => 'yiisoft/yii2-bootstrap',
'version' => '2.0.5.0',
'alias' =>
array (
'#yii/bootstrap' => $vendorDir . '/yiisoft/yii2-bootstrap',
),
),
'yiisoft/yii2-gii' =>
array (
'name' => 'yiisoft/yii2-gii',
'version' => '2.0.4.0',
'alias' =>
array (
'#yii/gii' => $vendorDir . '/yiisoft/yii2-gii',
),
),
);
I digged it a little bit. It seems problem is about the alias of the assets folder.
In GiiAsset.php file, there is this codeblock:
...
class GiiAsset extends AssetBundle
{
public $sourcePath = '#yii/gii/assets';
...
which returns
/var/projectsRoot/crmapp/src/vendor/yiisoft/yii2/gii/assets
but it normally should return
/var/projectsRoot/crmapp/src/vendor/yiisoft/gii/assets
so it is adding an unnecessary yii2 to the path.
I tried to change the $sourcePath in extensions.php file, but changing the value here does not effect the result in any way.
Any ideas?
--UPDATE--
While I was fiddling with things, I tried to define the alias to force the correct value; as follows:
Yii::setAlias('#yii/gii', $vendorDir . '/yiisoft/yii2-gii');
when I try to run the application with this setting I get following error:
The file or directory to be published does not exist: /var/projectsRoot/crmapp/src/vendor/bower/bootstrap/dist
When I change the alias definition to this:
Yii::setAlias('#yii/gii', $vendorDir . '/yiisoft/yii2-gi');
I get following error:
The file or directory to be published does not exist: /var/projectsRoot/crmapp/src/vendor/yiisoft/yii2-gi
I'm quite confused with this behavior. What would be causing this?
I ended up with deleting my vendor folder and composer.json file, and creating it back with following content:
{
"require": {
"codeception/codeception": "*",
"fzaninotto/faker": "*",
"yiisoft/yii2": "*",
"yiisoft/yii2-gii": "*"
}
}
When I launched the gii, it again threw the following exception:
The file or directory to be published does not exist:
/var/projectsRoot/crmapp/src/vendor/bower/jquery/dist
I renamed the vendor/bower-asset folder to vendor/bower and it works now.
I probably messed up with something before without noticing, but I'm not certain why it is looking for bower, instead of bower-asset. Renaming the bower-asset to bower seems to solve it.
UPDATE
Thanks to jacmoe from the original Yii forum, it has finally solved.
It seems these two lines need do be present in composer.json in order to automatically create bower folder, instead of bower-asset.
"extra": {
"asset-installer-paths": {
"npm-asset-library": "vendor/npm",
"bower-asset-library": "vendor/bower"
}
}
Original conversation can be found at here:
These lines are automatically created when you install the basic application template, but when installing the bare code base, you need to manually write them.
I have similar problem with my app based on yii2-app-advanced, but separated from #common. Solution is just add vendorPath attribute to application config.
I trying to access frontend/web from backend menu using alias
yii:yii2 advanced
webserver : XAMPP
IDE:net beans
codes I modified:
C:\xampp\htdocs\advanced\common\config\aliases.php
Yii::setAlias('fronthome', dirname(dirname(__DIR__)) . '/frontend/web/');
C:\xampp\htdocs\advanced\backend\views\layouts\main.php
if (Yii::$app->user->isGuest) {
$menuItems[] = ['label' => 'Login', 'url' => ['/site/login']];
$menuItems[] = ['label' => 'fronthome', 'url' => Yii::getAlias('#fronthome')];
but when accessing "fronthome" menu via backend menu; browser was returning the url:
http://localhost/advanced/backend/web/C:/xampp/htdocs/advanced/frontend/web
what i wanted browser to give:
http://localhost/advanced/frontend/web/
can some one please put some light... I searched but there was no elegant solution which I could find via alias.
Thanks
I got it working by making the below change
C:\xampp\htdocs\advanced\common\config\aliases.php
Yii::setAlias('fronthome', dirname(dirname(__DIR__)) . '/frontend/web/');
to
Yii::setAlias('fronthome', '../../frontend/web/');
As the links in the comments are outdated here is a snippet from the Yii2 docs:
Creating links from backend to frontend
Often it's required to create links from the backend application to the frontend application. Since the frontend application may contain its own URL manager rules you need to duplicate that for the backend application by naming it differently:
return [
'components' => [
'urlManager' => [
// here is your normal backend url manager config
],
'urlManagerFrontend' => [
// here is your frontend URL manager config
],
],
];
//After it is done, you can get an URL pointing to frontend like the following:
echo Yii::$app->urlManagerFrontend->createUrl(...);
current link to copy of relevant doc: https://yii2-framework.readthedocs.io/en/stable/guide/tutorial-advanced-app/
The way I have implemented this is to add a switch to my backend/config/bootstrap.php
switch (YII_ENV) {
case 'dev':
$frontend = 'https://my-domain.lan/';
break;
case 'test':
$frontend = 'https://my-domain.test/';
break;
case 'prod':
$frontend = 'https://my-domain.com/';
break;
}
and then in my backend/config/main.php I added the following
'urlManagerFrontend' => [
'class' => UrlManager::className(),
'enablePrettyUrl' => true,
'showScriptName' => false,
'baseUrl' => $frontend,
'rules' => [
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
]
],
and then where I want to use the frontend link:
echo Html::a('link',Yii::$app->urlManagerFrontend->createUrl('controller/view'))
Try using params.php
Add a key on params.php on your common/config folder
'frontendUrl' => 'http://frontendUrl/',
Then you could access it anywhere on your view by:
<?= Yii::$app->params['frontendUrl'] ?>
Hope this helps :)