Yii2 call the console command not from the project folder

Hello. I created the console command in Yii2:

projectDir/commands/SomeController.php
        
<?php
namespace app\commands;
            
use yii\console\Controller;

/**
 * Class SomeController
 * @package app\commands
 */
class SomeController extends Controller
{
    public function actionTest()
    {
        //do something
    }
}

I want to call this command in cron,and for testing I try to call it from the console, when I'm in the project folder:

php /var/www/projectDir/yii some/test

Everything works fine. But, if I call this command when I'm in a different directory, I get some errors.

First, i got

ReflectionException: Class app\admin\templates\Generator does not exist in /var/www/projectDir/vendor/yiisoft/yii2/di/Container.php:428

Seeing this, I commented configuration of gii in the file projectDir/common/config/config-console.php

After that I get an error:

Unknown command: some/test

Why is this happening? I call the command with an absolute path, and it works differently when called from different folders!

Upvotes: 0

Views: 901

Answers (1)

rob006
rob006

Reputation: 22144

You need to use magic constant __DIR__ to build absolute paths. Result of realpath('../../') will depend on path where you run command. You should use

$config['basePath'] = realpath(__DIR__ . '/../../')

or (probably better):

$config['basePath'] = dirname(dirname(__DIR__))

Upvotes: 2

Related Questions