14

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

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

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

4

1 回答 1

13

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

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 版本由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();
于 2014-03-15T13:14:22.267 回答