Yii2 Basic:Run 来自控制器操作的命令

Yii2 Basic:Run Command from Controller Action

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

我试过了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. 您没有将 'controllerNamespace' 设置为 'app\commands'
  2. 'basePath' 的值是错误的。如果您是来自 SiteController 的 运行,则值应为 __DIR__ . '/../'

我建议做一些不同的事情。再一次,假设您是来自 SiteController 的 运行,我会这样做:

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

这样您将使用与 运行 ./yii hello/index

时相同的配置