How to detect if I am in 'console' mode

2019-04-27 04:59发布

I am writing an app that runs from the browser. However, some model functions are also called from the Yii2 console. Therefore, I am getting errors when trying to access variables that are set in the GUI.

Is it possible to tell which mode I am in? Is there some environment variable automatically set, or should I just set some session variable in the console app to indicate the state?

标签: yii2
6条回答
可以哭但决不认输i
2楼-- · 2019-04-27 05:11

You can use

if (Yii::$app instanceof \yii\console\Application)

for console, and

if (Yii::$app instanceof \yii\web\Application)

for web.

查看更多
萌系小妹纸
3楼-- · 2019-04-27 05:16

Yii2 provides a number of different classes for application's console and for those of type web. In addition to this division of the mode of operation of the classes, there are also a set of rules governing the organization of the code of the application. The first, fundamental, it is the respect of giving the MVC Model object information, to view the management interface with the user and, finally, to the controller the role of coordination among them. In your case it seems to sense that a piece of code runs in console but referring to classes that provide a Web interface. Probably because in some Model classes were introduced with functions with HTML or other code that should not be there. If you need two separate applications should precisely separate applications that use a type controls

yii\console\Controller 

and another that uses controller type web

yii\web\Controller. 

Obviously Model classes will be common and, thanks to separate controller, be sure to invoke View appropriate to the type of user interface in use. I Hope this could be useful.

查看更多
Luminary・发光体
4楼-- · 2019-04-27 05:17

By default for console:

Yii::$app->id == 'basic-console'

And for web application:

Yii::$app->id == 'basic'

Yii::$app->id stores the id of the loaded configuration params. By default for console application it is 'basic-console' and for web application it is 'basic' (defined in configuration file)

查看更多
闹够了就滚
5楼-- · 2019-04-27 05:19

Correct variant

Yii::$app->request->isConsoleRequest
查看更多
淡お忘
6楼-- · 2019-04-27 05:22

Works for nginx and apache:

function isConsole()
{
    return 'cli' == php_sapi_name() || !array_key_exists('REQUEST_URI', $_SERVER);
}
查看更多
乱世女痞
7楼-- · 2019-04-27 05:31

There is a simpler way to figure this out without going through the Yii objects

if (php_sapi_name() == "cli") {
    return;
}

...and it works for all PHP scripts ...and it is lighter

查看更多
登录 后发表回答