shivaniverma6991
shivaniverma6991

Reputation: 330

Calling frontend controller yii2 using Shell not working

I am new to Yii2 Framework and I am trying to call my controller which is in the frontend folder below

htdocs/project/frontend/controllers/MyController.php

My method to be invoked is

actionTest_method()

In Terminal(in the project root directory), I am writing

php yii my/test_method

I tried

php yii frontend/controllers/my/test_method 

but didn't work Error, I am getting InvalidRouteException

Upvotes: 0

Views: 233

Answers (3)

Gobsek
Gobsek

Reputation: 91

liltle remark: if it is "advanced" template - console controllers locate in "console" folder, else if "basic" - in "command" folder

Upvotes: 1

Chanaka Karunarathne
Chanaka Karunarathne

Reputation: 2046

First of all. You don't need to call the Frontend controller from the console. if you want to do that. You can do with a curl command with the following URL pattern. Yii2 URL routing

curl GET 'example.com/my/action-name' 

But, as per the Yii2 guideline, you can use console commands to run a script from the console.

so your controller should be inside of the commands directory.

This is the helloController.php of the Yii2 basic app template.

<?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;
use yii\console\ExitCode;

/**
 * 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.
     * @return int Exit code
     */
    public function actionIndex($message = 'hello world')
    {
        echo $message . "\n";

        return ExitCode::OK;
    }
}

As you can see this extends yii\console\Controller which has the capability of running console commands with Yii2 features.

with this example code. you only need to run

php yii hello

and the script will output

hello world

in your case, create a MyController.php class extending yii\console\Controller inside the commands directory.

put the following code.

<?php
   
    namespace app\commands;
    
    use yii\console\Controller;
    
    class MyController extends Controller
    {
       
        public function actionTest_method()
        {
            echo 'I am test method';
    
        }
    }

and run

php yii my/test_method

in the root directory.

Upvotes: 1

kovenant
kovenant

Reputation: 46

Your console controller must be in htdocs/project/console/controllers/ Also check your console config for controllerNamespace

Upvotes: 0

Related Questions