如何使用没有Composer作为依赖项的命名空间的PHP库(PSR-0)?

问题描述 投票:12回答:1

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

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

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

php namespaces composer-php autoload psr-0
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,以便它适用于所有库。它取决于自动加载的标准以及如何命名库的类名。有时您必须在_上拆分类名并使用第一个元素作为direcotry名称,并将其添加到类名中。我有一个像Library_Parser这样的类的第二个库,但结构是Library/library-parser.php

第一个库直接使用上面的代码,所有类都自动加载。

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

https://stackoverflow.com/users/1740659/thibault的PSR-4版本:

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();
© www.soinside.com 2019 - 2024. All rights reserved.