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
How to I use Composer to autoload classes from outside the vendor?
提问by Tomasz Szymanek
I use psr-4
autoloader from composer:
我使用psr-4
Composer 的自动加载器:
"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 src
directory would be in your project root.
Its on the same level as vendor
directory 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\Munchkin
namespace would map to classes inside
该\DG\Munchkin
命名空间将映射到类中
/var/www/html/xxx/src/DG/Munch
and 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