How to detect if I am in 'console' mode

后端 未结 7 3408
死守一世寂寞
死守一世寂寞 2021-02-20 18:45

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 variabl

相关标签:
7条回答
  • 2021-02-20 19:01

    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

    0 讨论(0)
  • 2021-02-20 19:06

    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)

    0 讨论(0)
  • 2021-02-20 19:08

    Works for nginx and apache:

    function isConsole()
    {
        return 'cli' == php_sapi_name() || !array_key_exists('REQUEST_URI', $_SERVER);
    }
    
    0 讨论(0)
  • 2021-02-20 19:12

    You can use

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

    for console, and

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

    for web.

    0 讨论(0)
  • 2021-02-20 19:14

    Pure PHP:

    global $argv;
    if (empty($argv)) {
      // Browser mode
    }
    else {
      // Cli mode
    }
    
    0 讨论(0)
  • 2021-02-20 19:15

    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.

    0 讨论(0)
提交回复
热议问题