我在一个使用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自动加载。
编辑:为一个 namespace 添加对多个类路径的支持
EDIT2 :如果有人想改进此代码,则我创建了一个Github repo来处理此代码。
关于php - 没有 Composer 的PSR4自动加载,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39571391/