【问题标题】:Importing with composer without using require __DIR__ . '/vendor/autoload.php';使用 composer 导入而不使用 require __DIR__ 。 '/供应商/autoload.php';
【发布时间】:2021-11-04 18:16:20
【问题描述】:

我正在尝试了解如何在不使用 require __DIR__ . '/vendor/autoload.php'; 的情况下使用 composer 导入

这是我写的一个 Wordpress 插件:

<?php

use Google\Auth;

namespace google;

class GoogleClient
{


  function __construct($applicationName, $filePath) {
  }

  public function getClient($applicationName, $filepath)
  {

    $client = new Google_Client();

    return $client;
  }

}

Google_Client() 出现错误;我正在尝试使用 use 语法,但我不确定我需要在那里放置什么才能使其正常工作。

这是我的作曲家文件:

{
  "require": {
    "google/apiclient": "^2.10"
     }
}

这是我编写的另一个脚本,我确实使用了 composer 的自动加载器:

require __DIR__ . '/vendor/autoload.php';
    
function getClient() {
    $client = new Google_Client();
    return $client;
}

我可以从脚本中实例化Google_Client(),但我不能从我编写的插件中实例化。我不确定我需要从 google/apiclient 完全导入什么。我想我需要使用 Google/ApiClient,但该选项不存在。

这是我在 PHP 项目中的autoload_psr4.php 文件:

<?php

// autoload_psr4.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
    'Google\\Auth\\' => array($vendorDir . '/google/auth/src'),
    'Google\\' => array($vendorDir . '/asimlqt/php-google-spreadsheet-
);

不确定为什么使用 Google\Auth 似乎不起作用。我得到符号 Auth 已声明,但未使用,并且在 Google_Client() 上仍然出现错误;不确定是否只是 Visual Studio Code 无法确定没有错误,还是无法导入任何内容。

【问题讨论】:

  • 如果你不加载自动加载器,它应该如何找到你的文件?
  • 为什么不想使用 Composer 提供的自动加载器?自写的自动加载器看起来并没有太大的不同

标签: php composer-php


【解决方案1】:

很抱歉告诉你这个,但这是愚蠢的差事。没有意义。

如果您不导入 composer 的自动加载器,则需要读取每个包类,以便在您尝试实例化包中的类时找到它们。

但不仅如此。包本身depends on many other packages,因此可能会在某个时候尝试实例化任何这些类。您还需要导入(requireinclude那些 文件。这些包可能有多个类,和/或依赖于其他包等。

所以最后你会以任一结尾:

  • 代码中某处的大量 requires 列表(糟糕且效率低下)
  • 一个定制的自动加载器(浪费精力,你需要很长时间才能把它弄好,最好的情况是,它并不比作曲家的好。

帮自己一个忙,只需使用vendor/autoload.php

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 2013-09-02
    • 1970-01-01
    相关资源
    最近更新 更多