0

How can I run a command from controller action in basic template?

I tried How to run console command in yii2 from web

This fails:

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;
}

The above shows me Unknown command: hello/index Did you mean "help/index"?

The Command:

<?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 <[email protected]>
 * @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";

    }

}

Please help!

1 Answer 1

1

This is happening for two reasons.

  1. You didn't set the 'controllerNamespace' to 'app\commands'.
  2. The value of 'basePath' is wrong. If you're running this from the SiteController the value should be __DIR__ . '/../'

I recommend doing it a bit different. Again, lets say you're running it from SiteController, I would do it like this:

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

This way you'll use the same config as when running ./yii hello/index

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.