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

查看:506
本文介绍了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等.那么,作曲家可以调用文件夹功能中的所有文件吗?我懒惰使用

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.

注意:确保将include文件保留在/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天全站免登陆