简体   繁体   中英

Yii2 defining environment of console application

How to define environment of console application in Yii2? In web application it's simple. You just have to add custom declaration into Apache vhost configuration and you are done. For example:

Virtual host configuration:

SetEnv APPLICATION_ENV production

Yii2 entry script:

$env = !empty( $_SERVER['APPLICATION_ENV'] ) ? $_SERVER['APPLICATION_ENV'] : 'dev';

defined( 'YII_DEBUG' ) or define( 'YII_DEBUG', true );
defined( 'YII_ENV' ) or define( 'YII_ENV', $env );

I have three environments: development, testing, production. So how should I set appropriate environment in console app? Because each environment has specific configuration, etc.

My application is based on basic app template.

I had the same issue a few days ago. The yii console app can not read environment variables from VirtualHost settings.

My workaround is to call php_uname() function to get the full operation system name that PHP is running on, and use that to differentiate my environment. If your three environment are running on three different (virtual) machines, you can try this way.

php_uname doc

If the environment should always be the same for all console apps, it's a good idea to set it in config/console.php . Just add something like

defined('YII_ENV') or define('YII_ENV', 'console');

When the environment should be different for different machines, gethostname and a switch - case would represent the cleanest way to set the environment.

switch (gethostname()) {
case "machine1": define('YII_ENV', "console-test"); break;
// more case statements
default: define('YII_ENV', "console");

You can add lical file with environments, for example yii.env

<?php
defined('YII_ENV') or define('YII_ENV', 'prod');

and in file yii add:

if (is_file('yii.env')){
    include 'yii.env';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM