如何在基本模板中从控制器操作运行命令?
我尝试了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";
}
}
请帮忙!
答案 0 :(得分:1)
出现这种情况有两个原因。
'controllerNamespace'
设置为'app\commands'
。'basePath'
的值是错误的。如果您从SiteController运行此值,则值应为__DIR__ . '/../'
我建议做的有点不同。再说一次,让我们说你从SiteController运行它,我会这样做:
$config = require(__DIR__ . '/../config/console.php');
$console = new \yii\console\Application($config);
这样您就可以使用与运行./yii hello/index