Yii2 Basic:从Controller Action运行命令

时间:2017-03-10 11:30:29

标签: console yii2 yii2-basic-app

如何在基本模板中从控制器操作运行命令?

我尝试了How to run console command in yii2 from web

这失败了:

public function actionTest(){
    $oldApp = \Yii::$app;
    $console = new \yii\console\Application([
        'id' => 'basic-console',
        'basePath' => '@app/commands',
        'components' => [
            'db' => $oldApp->db,
        ],
    ]);
    \Yii::$app->runAction('hello/index');
    \Yii::$app = $oldApp;
}

以上显示我Unknown command: hello/index Did you mean "help/index"?

命令:

<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace app\commands;

use yii\console\Controller;

/**
 * This command echoes the first argument that you have entered.
 *
 * This command is provided as an example for you to learn how to create console commands.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class HelloController extends Controller
{
    /**
     * This command echoes what you have entered as the message.
     * @param string $message the message to be echoed.
     */
    public function actionIndex($message = 'hello world')
    {
        echo $message . "\n";

    }

}

请帮忙!

1 个答案:

答案 0 :(得分:1)

出现这种情况有两个原因。

  1. 您没有将'controllerNamespace'设置为'app\commands'
  2. 'basePath'的值是错误的。如果您从SiteController运行此值,则值应为__DIR__ . '/../'
  3. 我建议做的有点不同。再说一次,让我们说你从SiteController运行它,我会这样做:

        $config  = require(__DIR__ . '/../config/console.php');
        $console = new \yii\console\Application($config);
    

    这样您就可以使用与运行./yii hello/index

    时相同的配置