包含作曲家软件包的分布式PHP插件的自动加载器 [英] Autoloader for distributed PHP plugins that includes composer packages

查看:139
本文介绍了包含作曲家软件包的分布式PHP插件的自动加载器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与要求用户上传扩展名的CMS合作.

I am working with a CMS that requires the user to upload extensions.

用户无权访问作曲家.因此,我需要将依赖项包括在发行版本身中.

The users do not have access to composer. So I will need to include the dependencies in the distribution itself.

我将如何实现它来自动加载所有依赖项?这是解决这个问题的方法吗?

这是分布式扩展的简化目录结构. (用户应该上传上载目录的内容):

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

autoload.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

MyClass.php

namespace Eg;

require './autoload.php';

use GuzzleHttp;

class MyClass {
}

侧面说明:我正在编写的应用程序实际上是自动构建"扩展名的.从作曲家的"vendor"文件夹中复制依赖项是自动完成的.

Side note: The application I am writing actually "builds" the extension automatically. The copying of dependencies from composer's "vendor" folder is done automatically.

推荐答案

用户无权访问作曲家.因此,我需要将依赖项包括在发行版本身中.

The users do not have access to composer. So I will need to include the dependencies in the distribution itself.

您正在这里重新发明轮子. Composer是开源的,因此我只需要看一下并检查是否可以重用其代码和逻辑即可.您也许可以轻松摆脱90%的代码,但是autoloader和composer.json扫描应该是您所需要的.

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. 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.

这篇关于包含作曲家软件包的分布式PHP插件的自动加载器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆