我在一个项目中有一个包,它是使用 composer 和 composer.json 条目自动加载的,如下所示:
"autoload": {
"psr-4": {
"CompanyName\\PackageName\\": "packages/package-folder/src/"
}
}
现在我将其复制到另一个未使用 Composer 的项目中。我怎样才能在那里自动加载同一个包?
最佳答案
您必须阅读 composer 并自行为 composer.json
中定义的每个命名空间加载类。
方法如下:
function loadPackage($dir)
{
$composer = json_decode(file_get_contents("$dir/composer.json"), 1);
$namespaces = $composer['autoload']['psr-4'];
// Foreach namespace specified in the composer, load the given classes
foreach ($namespaces as $namespace => $classpaths) {
if (!is_array($classpaths)) {
$classpaths = array($classpaths);
}
spl_autoload_register(function ($classname) use ($namespace, $classpaths, $dir) {
// Check if the namespace matches the class we are looking for
if (preg_match("#^".preg_quote($namespace)."#", $classname)) {
// Remove the namespace from the file path since it's psr4
$classname = str_replace($namespace, "", $classname);
$filename = preg_replace("#\\\\#", "/", $classname).".php";
foreach ($classpaths as $classpath) {
$fullpath = $dir."/".$classpath."/$filename";
if (file_exists($fullpath)) {
include_once $fullpath;
}
}
}
});
}
}
loadPackage(__DIR__."/vendor/project");
new CompanyName\PackageName\Test();
当然,我不知道你在PackageName中有哪些类。
/vendor/project
是克隆或下载外部库的地方。这是您拥有 composer.json
文件的地方。
注意:这仅适用于 psr4 自动加载。
编辑:为一个命名空间添加对多个类路径的支持
EDIT2 :我创建了一个 Github repo处理这段代码,如果有人想改进它。
关于php - 没有 Composer 的 PSR 4 自动加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39571391/