【问题标题】:How to use composer's autoload when I already use autoload?当我已经使用自动加载时如何使用作曲家的自动加载?
【发布时间】:2018-06-29 23:35:45
【问题描述】:

我有一个 config.php 文件,我在其中为我的所有个人课程使用自动加载

function __autoload($class_name) {
    include __DIR__.'/classes/'.$class_name . '.php';
}

我现在需要使用来自作曲家的第 3 方课程,该课程位于 /vendor/guzzlehttp.

所以我现在的代码是:

require('Config.php'); // my config file: this is used in ALL site
require 'vendor/autoload.php'; // the copmoser 
$client = new GuzzleHttp\Client([]); // call to the 3rd party class installed by composer

引发 404 错误:php 在 /classes 中搜索 GuzzleHttp

未捕获的错误:找不到类“GuzzleHttp\Client”

我不知道如何解决这个问题:我需要在 /classes 中保留自己的课程

我需要自动加载它们,因为所有网站都使用它。

那么:如何在我的网站上使用 composer 安装的类?

我的 composer.json 内容是:

{
    "require": {
        "firebase/php-jwt": "^5.0"
    }
}

【问题讨论】:

    标签: php composer-php


    【解决方案1】:

    自动加载器可以很好地堆叠,但您需要先检查文件是否存在,然后再尝试包含它。

    但是,如果您已经在使用 Composer,只需让 Composer 处理自动加载。

    添加对从 composer.json 的自动加载 PSR-4 部分中的类目录加载的全局命名空间的引用:

    "autoload": {
        "psr-4": {
            "": "classes"
        }
    },
    

    【讨论】:

    • 我的 composer.json 包含那个(并且只有那个):{ "require": { "firebase/php-jwt": "^5.0" } }
    • 在倒数第二个大括号后添加逗号,添加此部分(不带结尾逗号),然后运行composer dump-autoload。
    【解决方案2】:

    __autoload() 已被弃用,并且似乎与 Composer 使用的当前最佳实践 spl_autoload_register() 不兼容。

    function myAutoload($class_name) {
        include __DIR__.'/classes/'.$class_name . '.php';
    }
    spl_autoload_register('myAutoload');
    

    但是你真的应该考虑将你的依赖项移动到你已经拥有的依赖项管理器中,Composer。

    对于 Composer 中已经存在的外部库,例如 Guzzle:https://packagist.org/packages/guzzlehttp/guzzle

    对于内部开发的库:https://getcomposer.org/doc/04-schema.md#autoload

    编辑:再看一遍,@Devon 的回答没有理由不起作用。

    【讨论】:

      猜你喜欢
      • 2018-08-26
      • 1970-01-01
      • 2013-12-09
      • 2013-03-05
      • 2015-09-24
      • 2023-03-26
      • 2021-12-18
      • 2014-01-31
      相关资源
      最近更新 更多