简体   繁体   English

Yii2不是从项目文件夹中调用控制台命令

[英]Yii2 call the console command not from the project folder

Hello. 你好。 I created the console command in Yii2: 我在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: 我想在cron中调用此命令,为了进行测试,当我在项目文件夹中时,尝试从控制台调用它:

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 看到这一点,我在文件projectDir/common/config/config-console.php评论了gii的配置。

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! 我使用绝对路径调用该命令,并且从不同文件夹中调用该命令时,它的工作方式有所不同!

You need to use magic constant __DIR__ to build absolute paths. 您需要使用魔术常数__DIR__来构建绝对路径。 Result of realpath('../../') will depend on path where you run command. realpath('../../')将取决于您运行命令的路径。 You should use 你应该用

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

or (probably better): 或(可能更好):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM