我如何在 Yii2 的供应商库中需要一个尚未包含的文件或 class?

How do I require a file or class in a vendor library in Yii2 that is not already included?

我有一个 Yii2 看不到的 class。所有其他 class 都可以。我尝试了以下。注释行不起作用。

// use app\vendor\googleads\googleads-php-lib\src\Google\Api\Ads\Common\Util\ErrorUtils;
// require_once UTIL_PATH . '/ErrorUtils.php';
require_once('../vendor/googleads/googleads-php-lib/src/Google/Api/Ads/Common/Util/ErrorUtils.php');
use \ErrorUtils;

这行得通,但看起来不对。而且它在我需要的命令模式下不起作用。

$ yii cron
PHP Warning:  Uncaught exception 'yii\base\ErrorException' with message 'require_once(../vendor/googleads/googleads-php-lib/src/Google/Api/Ads/Common/Util/ErrorUtils.php): failed to open stream: No such file or directory' in /cygdrive/c/Users/Chloe/workspace/xxx/models/GoogleAdWords.php:36

如何在 Yii2 中要求或使用这个 class?

您使用的库不为其 类 提供 psr-4 自动加载器设置。您需要将要加载的 类 的 autoload classmap 添加到项目根目录中的 composer.json 中,如下所示:

"autoload": {
    "classmap": [
      "vendor/googleads/googleads-php-lib/src/Google/Api/Ads/Common/Lib",
      "vendor/googleads/googleads-php-lib/src/Google/Api/Ads/Common/Util"
    ]
},

然后在您的控制台中:composer dump-autoload

这将更新作曲家自动加载器。之后,您将能够调用库 类:\ErrorUtils::GetSourceOperationIndex($error)

首先添加到作曲家(shell 命令):

$ composer require googleads/googleads-php-lib

然后简单地使用 te class:

\ErrorUtils::GetApiErrors($var);

请注意,googleads 不使用命名空间,因此它是“\”NS