简体   繁体   English

用于包含 Composer 包的分布式 PHP 插件的自动加载器

[英]Autoloader for distributed PHP plugins that includes composer packages

I am working with a CMS that requires the user to upload extensions.我正在使用需要用户上传扩展的 CMS。

The users do not have access to composer.用户无权访问作曲家。 So I will need to include the dependencies in the distribution itself.所以我需要在发行版本身中包含依赖项。

Would how I implement it work for autoloading all dependencies?我如何实现它以自动加载所有依赖项? Is this the way to go about this?这是解决这个问题的方法吗?

Here's the simplified directory structure of the distributed extension.这是分布式扩展的简化目录结构。 (The user is supposed to upload the contents of the upload directory): (用户应该上传上传目录的内容):

upload/Eg/
upload/Eg/autoload.php <-- autoloader to load the dependencies
upload/Eg/MyClass.php <-- requires autoload.php
upload/Eg/dependencies <-- where required composer packages are copied
upload/Eg/dependencies/guzzlehttp <-- for example

autoload.php自动加载.php

spl_autoload_register(function ($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';

    require $fileName;
});

MyClass.php我的类.php

namespace Eg;

require './autoload.php';

use GuzzleHttp;

class MyClass {
}

Side note: The application I am writing actually "builds" the extension automatically.旁注:我正在编写的应用程序实际上会自动“构建”扩展。 The copying of dependencies from composer's "vendor" folder is done automatically.从 Composer 的“供应商”文件夹复制依赖项是自动完成的。

The users do not have access to composer.用户无权访问作曲家。 So I will need to include the dependencies in the distribution itself.所以我需要在发行版本身中包含依赖项。

You are reinventing the wheel here.你在这里重新发明轮子。 Composer is open source so I'd simply take a look and check if I can reuse its code and logic. Composer 是开源的,所以我只是看看并检查我是否可以重用它的代码和逻辑。 You'd probably be able to easily get rid of 90% of the code, yet the autoloader and composer.json scanning should be all you need.您可能能够轻松删除 90% 的代码,但您只需要自动加载器和 composer.json 扫描即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM