How can I call a console command in web application in Yii 2.0

后端 未结 5 903
余生分开走
余生分开走 2020-12-19 13:37

I have a console command to generate user report. I want to call the same from my web application. I am using Yii 2.0.0 beta version.I tried to follow answers given in this

相关标签:
5条回答
  • 2020-12-19 13:51

    use this code:

    $application = new yii\console\Application($config);
    $application->runAction('controller/action');
    

    I'm using this method instead of yii console command, because I'm running Yii on managed VPS where unix commands are not supported in cron, only php scripts.

    To run it this way instead of console, the yii configuration must be initialized first, of course:

    defined('YII_DEBUG') or define('YII_DEBUG', true);
    defined('YII_ENV') or define('YII_ENV', 'dev');
    
    require(__DIR__ . '/vendor/autoload.php');
    require(__DIR__ . '/vendor/yiisoft/yii2/Yii.php');
    require(__DIR__ . '/common/config/bootstrap.php');
    require(__DIR__ . '/console/config/bootstrap.php');
    
    $config = yii\helpers\ArrayHelper::merge(
        require(__DIR__ . '/common/config/main.php'),
        require(__DIR__ . '/common/config/main-local.php'),
        require(__DIR__ . '/console/config/main.php'),
        require(__DIR__ . '/console/config/main-local.php')
    );
    
    0 讨论(0)
  • 2020-12-19 13:54

    If you really want to run Console controller by Web controller likes migrate:

    public function actionMigrate()
    {
        // Keep current application
        $oldApp = \Yii::$app;
        // Load Console Application config
        $config = require \Yii::getAlias('@app'). '/config/console.php';
        new \yii\console\Application($config);
        $result = \Yii::$app->runAction('migrate', ['migrationPath' => '@app/migrations/', 'interactive' => false]);
        // Revert application
        \Yii::$app = $oldApp;
        return;
    }
    

    Above sample code is for yii2-app-basic template, you could change path for yii2-app-advanced template.

    0 讨论(0)
  • 2020-12-19 13:57

    You should use an extension like https://github.com/vova07/yii2-console-runner-extension

    0 讨论(0)
  • 2020-12-19 13:59

    yii2-console-runner-extension keeps loading.

    Try this:

    It's yii (without ext, not yii.bat)

    Make sure that php folder added to PATH variable (Windows)

    $op = shell_exec ( 'absolute/path/to/yii ' . 'cache/flush-all' );
    \yii\helpers\VarDumper::dump($op, 10, 1);
    

    Output:

    The following cache components were processed:
    
    * cache (yii\\caching\\FileCache)
    
    0 讨论(0)
  • 2020-12-19 14:07

    I think this is the simplest solution:

    $controller = new YourConsoleController(Yii::$app->controller->id, Yii::$app);
    $controller->actionYourConsoleAction();
    
    0 讨论(0)
提交回复
热议问题