php 如何使用 Composer 从供应商外部自动加载类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28253154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:46:37  来源:igfitidea点击:

How to I use Composer to autoload classes from outside the vendor?

phpcomposer-phpautoload

提问by Tomasz Szymanek

I use psr-4autoloader from composer:

我使用psr-4Composer 的自动加载器:

"autoload": {
    "psr-4": {
        "DG\Munchkin\": "src/DG/Munch/"
    }
}

This loads classes from /var/www/html/xxx/vendor/yyy/src/DG/Munch

这从 /var/www/html/xxx/vendor/yyy/src/DG/Munch

But how can I load classes from /var/www/html/xxx/?

但是我如何从 加载类/var/www/html/xxx/

I wrote my own autoloader, but when I require vendor/autoload.php(composer autoload) and my autoloader, it won't work until I create instance of a class in my own autoloader.

我编写了自己的自动加载器,但是当我需要vendor/autoload.php(composer autoload) 和我的自动加载器时,只有在我自己的自动加载器中创建类的实例后,它才能工作。

回答by Jens A. Koch

The srcdirectory would be in your project root. Its on the same level as vendordirectory is.

src目录将在您的项目根目录中。它与vendor目录处于同一级别。

If you define

如果你定义

"autoload": {
    "psr-4": {
        "DG\Munchkin\": "src/DG/Munch/"
    }
}

this will not load classes from /var/www/html/xxx/vendor/yyy/src/DG/Munch, like you stated.

这不会/var/www/html/xxx/vendor/yyy/src/DG/Munch像您所说的那样从 加载类。

Because your project structure is:

因为你的项目结构是:

/var/www/html/
 +- /xxx (project)
     - composer.json
     +- /src
        +- DG
           +- Munch
     +- /vendor
        - autoload.php
        +- vendor-projectA
        +- vendor-projectB
        +- yyy

The \DG\Munchkinnamespace would map to classes inside

\DG\Munchkin命名空间将映射到类中

/var/www/html/xxx/src/DG/Munchand not inside

/var/www/html/xxx/src/DG/Munch而不是里面

/var/www/html/xxx/vendor/yyy/src/DG/Munch.

/var/www/html/xxx/vendor/yyy/src/DG/Munch.

But how can I load classes from /var/www/html/xxx/?

但是如何从 /var/www/html/xxx/ 加载类?

Define the paths in the composer.json (inside /var/www/html/xxx/) of your project:

在您的项目的 composer.json(在 /var/www/html/xxx/ 内)中定义路径:

"autoload": {
    "psr-4": {
        "ProjectRoot\" : "", 
        "NamspaceInSourceDir\" : "src/"         
    }
 }

or load the composer autoloader in your index.php or during it's bootstrap and add the paths manually:

或在 index.php 中或在引导过程中加载 Composer 自动加载器并手动添加路径:

$loader = require 'vendor/autoload.php';
$loader->add('Namespace\Somewhere\Else\', __DIR__);
$loader->add('Namespace\Somewhere\Else2\', '/var/www/html/xxx');

Referencing: https://getcomposer.org/doc/04-schema.md#autoload

参考:https: //getcomposer.org/doc/04-schema.md#autoload