php 使用 Composer 的自动加载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12818690/
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 04:17:46  来源:igfitidea点击:

Using Composer's Autoload

phpautoloadcomposer-php

提问by Chris R

I have been looking around the net with no luck on this issue. I am using composer's autoload with this code in my composer.json:

我一直在网上环顾四周,但在这个问题上没有运气。我在我的以下代码中使用 composer 的自动加载composer.json

"autoload": {
    "psr-0": {"AppName": "src/"}
}

But I need to autoload at a higher level than the vendor folder.

但是我需要在比供应商文件夹更高的级别自动加载。

Doing something like this does not work:

这样做是行不通的:

"autoload": {
    "psr-0": {"AppName": "../src/"}
}

Does anyone know a fix or how I can do this?

有谁知道修复方法或我如何做到这一点?

回答by Seldaek

Every package should be responsible for autoloading itself, what are you trying to achieve with autoloading classes that are out of the package you define?

每个包都应该负责自动加载本身,你想用你定义的包之外的自动加载类来实现什么?

One workaround if it's for your application itself is to add a namespace to the loader instance, something like this:

如果是针对您的应用程序本身,一种解决方法是向加载程序实例添加命名空间,如下所示:

<?php

$loader = require 'vendor/autoload.php';
$loader->add('AppName', __DIR__.'/../src/');

回答by Sergiy Sokolenko

The composer documentationstates that:

作曲家的文件指出:

After adding the autoload field, you have to re-run install to re-generate the vendor/autoload.php file.

添加 autoload 字段后,您必须重新运行 install 以重新生成 vendor/autoload.php 文件。

Assuming your "src" dir resides at the same level as "vendor" dir:

假设您的“src”目录与“供应商”目录位于同一级别:

  • src
    • AppName
  • vendor
  • composer.json
  • 源文件
    • 应用名称
  • 小贩
  • 作曲家.json

the following config is absolutely correct:

以下配置是绝对正确的:

{
    "autoload": {
        "psr-0": {"AppName": "src/"}
    }
}

but you must re-update/install dependencies to make it work for you, i.e. run:

但是您必须重新更新/安装依赖项以使其适合您,即运行:

php composer.phar update

This command will get the latest versions of the dependencies and update the file "vendor/composer/autoload_namespaces.php" to match your configuration.

此命令将获取最新版本的依赖项并更新文件“vendor/composer/autoload_namespaces.php”以匹配您的配置。

Also as noted by @Dom, you can use composer dump-autoloadto update the autoloader without having to go through an update.

同样正如@Dom 所指出的,您可以使用composer dump-autoload来更新自动加载器,而无需进行更新。

回答by Francesco Casula

There also other ways to use the composer autoload features. Ways that can be useful to load packages without namespaces or packages that come with a custom autoload function.

还有其他方法可以使用 Composer 自动加载功能。加载没有命名空间的包或带有自定义自动加载功能的包的方法。

For example if you want to include a single file that contains an autoload function as well you can use the "files" directive as follows:

例如,如果您想包含一个包含自动加载功能的单个文件,您可以使用“files”指令,如下所示:

"autoload": {
    "psr-0": {
        "": "src/",
        "SymfonyStandard": "app/"
    },
    "files": ["vendor/wordnik/wordnik-php/wordnik/Swagger.php"]
},

And inside the Swagger.phpfile we got:

Swagger.php我们得到的文件中:

function swagger_autoloader($className) {
    $currentDir = dirname(__FILE__);
    if (file_exists($currentDir . '/' . $className . '.php')) {
        include $currentDir . '/' . $className . '.php';
    } elseif (file_exists($currentDir . '/models/' . $className . '.php')) {
        include $currentDir . '/models/' . $className . '.php';
    }
}
spl_autoload_register('swagger_autoloader');

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

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

Otherwise you may want to use a classmap reference:

否则,您可能需要使用类映射引用:

{
    "autoload": {
        "classmap": ["src/", "lib/", "Something.php"]
    }
}

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

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

Note:during your tests remember to launch the composer dump-autoloadcommand or you won't see any change!

注意:在您的测试期间,请记住启动 composerdump-autoload命令,否则您将看不到任何更改!

./composer.phar dump-autoload

Happy autoloading =)

快乐自动加载 =)

回答by nayak

In my opinion, Sergiy'sanswer should be the selected answer for the given question. I'm sharing my understanding.

在我看来,Sergiy 的答案应该是给定问题的选定答案。我分享一下我的理解。

I was looking to autoload my package files using composer which I have under the dir structure given below.

我正在寻找使用 Composer 自动加载我的包文件,我在下面给出的目录结构下。

<web-root>
    |--------src/
    |           |--------App/
    |           |
    |           |--------Test/
    |
    |---------library/
    |
    |---------vendor/
    |           |
    |           |---------composer/
    |           |           |---------autoload_psr4.php
    |           |           
    |           |----------autoload.php
    |
    |-----------composer.json
    |

I'm using psr-4autoloading specification.

我正在使用psr-4自动加载规范。

Had to add below lines to the project's composer.json. I intend to place my class files inside src/App , src/Test and library directory.

必须将以下几行添加到项目的 composer.json 中。我打算将我的类文件放在 src/App 、 src/Test 和 library 目录中。

"autoload": {
        "psr-4": {
            "OrgName\AppType\AppName\": ["src/App", "src/Test", "library/"]
        }
    } 

This is pretty much self explaining. OrgName\AppType\AppNameis my intended namespace prefix. e.g for class User in src/App/Controller/Provider/User.php-

这几乎是自我解释。OrgName\AppType\AppName是我想要的命名空间前缀。例如对于src/App/Controller/Provider/User.php 中的类 User -

namespace OrgName\AppType\AppName\Controller\Provider; // namespace declaration

use OrgName\AppType\AppName\Controller\Provider\User; // when using the class

Also notice "src/App", "src/Test" .. are from your web-root that is where your composer.json is. Nothing to do with the vendor dir. take a look at vendor/autoload.php

还要注意 "src/App", "src/Test" .. 来自您的 web 根目录,即您的 composer.json 所在的位置。与供应商目录无关。看看 vendor/autoload.php

Now if composer is installed properly all that is required is #composer update

现在,如果Composer安装正确,所有需要的就是 #composer update

After composer update my classes loaded successfully. What I observed is that composer is adding a line in vendor/composer/autoload_psr4.php

作曲家更新我的类成功加载后。我观察到的是 composer 在 vendor/composer/autoload_psr4.php 中添加了一行

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'Monolog\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
    'OrgName\AppType\AppName\' => array($baseDir . '/src/App', $baseDir . '/src/Test', $baseDir . '/library'),
);

This is how composer maps. For psr-0 mapping is in vendor/composer/autoload_classmap.php

这就是作曲家映射的方式。对于 psr-0 映射在 vendor/composer/autoload_classmap.php

回答by JamesHalsall

Just create a symlink in your src folder for the namespace pointing to the folder containing your classes...

只需在 src 文件夹中为指向包含类的文件夹的命名空间创建一个符号链接...

ln -s ../src/AppName ./src/AppName

Your autoload in composer will look the same...

您在作曲家中的自动加载看起来相同......

"autoload": {
    "psr-0": {"AppName": "src/"}
}

And your AppName namespaced classes will start a directory up from your current working directory in a srcfolder now... that should work.

并且您的 AppName 命名空间类将从您当前工作目录中的src文件夹中启动一个目录……这应该可以工作。

回答by acme

The autoload config does start below the vendor dir. So you might want change the vendor dir, e.g.

自动加载配置确实在供应商目录下启动。所以你可能想改变供应商目录,例如

{
    "config": {
        "vendor-dir": "../vendor/"
    },
    "autoload": {
        "psr-0": {"AppName": "src/"}
    }
}

Or isn't this possible in your project?

或者这在您的项目中是不可能的?