Composer 自动加载文件夹中的多个文件 [英] Composer Autoload Multiple Files in Folder

查看:35
本文介绍了Composer 自动加载文件夹中的多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的最新项目中使用 composer 并像这样映射我的函数

I'm using composer in my latest project and mapping my function like this

"require": {
    ...
},
"require-dev": {
    ...
},
"autoload": {
    "psr-4": {
        ...
    },
    "files": [
        "src/function/test-function.php"
    ]
}

我想象一个文件夹函数中会有很多文件,例如:real-function-1.php、real-function-2.php等.那么,composer可以调用文件夹函数中的所有文件吗?我懒得用

I imagine there will be a lot of files in a folder function, ex : real-function-1.php, real-function-2.php, etc. So, can composer call all the files in the folder function ? i lazy to use

"files": [
     "src/function/real-function-1.php",
     "src/function/real-function-2.php",
     ..,
     "src/function/real-function-100.php",
]

有没有像我这样的懒人...

Is there any lazy like me...

推荐答案

如果你不能命名你的函数(因为它会破坏一堆代码,或者因为你不能使用 PSR-4),并且你不不想创建包含您的函数的静态类(然后可以自动加载),您可以创建自己的全局包含文件,然后告诉作曲家包含它.

If you can't namespace your functions (because it will break a bunch of code, or because you can't use PSR-4), and you don't want to make static classes that hold your functions (which could then be autoloaded), you could make your own global include file and then tell composer to include it.

composer.json

{
    "autoload": {
        "files": [
            "src/function/include.php"
        ]
    }
}

include.php

$files = glob(__DIR__ . '/real-function-*.php');
if ($files === false) {
    throw new RuntimeException("Failed to glob for function files");
}
foreach ($files as $file) {
    require_once $file;
}
unset($file);
unset($files);

这是不理想的,因为它会为每个请求加载每个文件,无论其中的函数是否被使用,但它会起作用.

This is non-ideal since it will load every file for each request, regardless of whether or not the functions in it get used, but it will work.

注意:确保将包含文件保存在/real-function 或类似目录之外.或者它也会包含自身并变成递归函数并最终抛出内存异常.

Note: Make sure to keep the include file outside of your /real-function or similar directory. Or it will also include itself and turn out to be recursive function and eventually throw a memory exception.

这篇关于Composer 自动加载文件夹中的多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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