且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

没有作曲家的PSR4自动加载

更新时间:2023-11-17 09:20:22

您必须阅读作曲家并为定义在composer.json中的每个命名空间自己加载类.

You have to read the composer and load the classes yourself for each namespaces defined into the 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文件的地方.

Of course, I don't know the classes you have in the PackageName. The /vendor/project is where your external library was cloned or downloaded. This is where you have the composer.json file.

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

Note: this works only for psr4 autoload.

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

EDIT : Adding support for multiple classpaths for one namespace

EDIT2 :我创建了一个 Github存储库来处理此代码,如果有人想对其进行改进.

EDIT2 : I created a Github repo to handle this code, if anyone wants to improve it.