PSR4自动加载没有作曲家

Hap*_*der 4 php autoload composer-php

我在一个项目中有一个包,它使用composer和composer.json条目自动加载如下:

 "autoload": {
      "psr-4": {
        "CompanyName\\PackageName\\": "packages/package-folder/src/"
    }
  }
Run Code Online (Sandbox Code Playgroud)

现在我将其复制到另一个不使用composer的项目中.我怎么能在那里自动加载这个相同的包?

Thi*_*ult 15

您必须阅读作曲家并自己为每个定义到的名称空间加载类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();
Run Code Online (Sandbox Code Playgroud)

当然,我不知道您在PackageName中拥有的类.这/vendor/project是克隆或下载外部库的地方.这是您拥有该composer.json文件的位置.

注意:这仅适用于psr4自动加载.

编辑:为一个命名空间添加对多个类路径的支持

EDIT2:我创建了一个Github仓库来处理这段代码,如果有人想改进的话.


小智 7

是的,这个问题已经有 6 个月了,但是我只使用了以下内容。我刚刚找到了以下问题的解决方案。我只是composer dump-autoload -o在我的项目文件夹中本地运行了命令。之后,我只需将 ./vendor/composer 文件夹和 /vendor/autoload.php 的内容上传到服务器,然后它又可以工作了。这在您无法在服务器上运行 Composer 的情况下很有帮助。