这真是一个令人讨厌的问题。我为作曲家提交了功能请求:https ://github.com/composer/composer/issues/6768
应该有一种方法可以指定自动加载的操作顺序,以便可以在“require”或“require-dev”部分的任何类之前加载您的自定义“文件”;任何需要您在 vendor/ 内编辑 3rd 方包的解决方案充其量都是 hacky,但目前,我认为没有其他好的选择。
我能想到的最好的办法是使用脚本来修改 vendor/autoload.php 以便它在包含任何自动加载类之前强制包含您的文件。这是我的modify_autoload.php:
<?php
/**
* Updates the vendor/autoload.php so it manually includes any files specified in composer.json's files array.
* See https://github.com/composer/composer/issues/6768
*/
$composer = json_decode(file_get_contents('composer.json'));
$files = (property_exists($composer, 'files')) ? $composer->files : [];
if (!$files) {
print "No files specified -- nothing to do.\n";
exit;
}
$patch_string = '';
foreach ($files as $f) {
$patch_string .= "require_once __DIR__ . '/../{$f}';\n";
}
$patch_string .= "require_once __DIR__ . '/composer/autoload_real.php';";
// Read and re-write the vendor/autoload.php
$autoload = file_get_contents(__DIR__ . '/vendor/autoload.php');
$autoload = str_replace("require_once __DIR__ . '/composer/autoload_real.php';", $patch_string, $autoload);
file_put_contents(__DIR__ . '/vendor/autoload.php', $autoload);
您可以手动运行它,也可以通过将它添加到 composer.json 脚本让 composer 运行它:
{
// ...
"scripts": {
"post-autoload-dump": [
"php modify_autoload.php"
]
}
// ...
}