PSR4 auto load without composer

柔情痞子 提交于 2019-11-29 07:59:23

You have to read the composer and load the classes yourself for each namespaces defined into the composer.json.

Here is how :

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();

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.

Note: this works only for psr4 autoload.

EDIT : Adding support for multiple classpaths for one namespace

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

Yes, this question is 6months old, however I just used the following. I just found the following solution to the problem. I just locally ran the command composer dump-autoload -o in my project folder. After that I simply had to upload the contents of ./vendor/composer folder and the /vendor/autoload.php to the server and it worked again. This is helpful in case you cannot run composer on the server.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!