Skip to content
Advertisement

Yii2 call the console command not from the project folder

Hello. I created the console command in Yii2:

projectDir/commands/SomeController.php
        
<?php
namespace appcommands;
            
use yiiconsoleController;

/**
 * Class SomeController
 * @package appcommands
 */
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 appadmintemplatesGenerator 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!

Advertisement

Answer

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__))
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement