如何使用带有名称空间的PHP库,而不依赖于Composer (PSR-0)


How to use a PHP library with namespacing without Composer as dependency (PSR-0)?

我需要使用一些PHP库与依赖关系,但我对客户端的web服务器有一些限制。这是一个托管的web服务器,我不能使用控制台,例如通过SSH。

那么我现在如何使用这些库没有Composer?
我可以手动创建一些目录吗?我需要创建哪些目录或路径?此外,我需要创建什么才能使自动加载和命名空间工作?

我可以手动创建autoload.php文件的内容是什么?

使用一个简单的自动加载器是可能的,并且做到这一点并不难:

function __autoload($className)
{
    $className = ltrim($className, '''');
    $fileName  = '';
    $namespace = '';
    if ($lastNsPos = strripos($className, '''')) {
        $namespace = substr($className, 0, $lastNsPos);
        $className = substr($className, $lastNsPos + 1);
        $fileName  = str_replace('''', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
    }
    $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
    // $fileName .= $className . '.php'; //sometimes you need a custom structure
    //require_once "library/class.php"; //or include a class manually
    require $fileName;
}

但有时你必须调整$fileName,使其适用于所有库。这取决于自动加载的标准以及库的类名的命名方式。有时您必须拆分_上的类名,并使用第一个元素作为目录名,并将其也添加到类名中。例如,我有一个类似Library_Parser的类的第二个库,但结构是Library/library-parser.php

第一个库直接与上面的代码一起工作,所有的类都被自动加载。

代码取自http://www.sitepoint.com/autoloading-and-the-psr-0-standard/,但我不得不纠正一些代码部分(额外的下划线和反斜杠)。我已经使用了PSR-0标准解决方案。

PSR-4 version by https://stackoverflow.com/users/1740659/thibault:

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