Composer Autoload Multiple Files in Folder

∥☆過路亽.° 提交于 2020-04-08 08:46:44

问题


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"
    ]
}

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


回答1:


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.

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.




回答2:


There's actually a better way to do this now without any custom code. You can use Composer's classmap feature if you're working with classes. If you're working with individual files that contain functions then you will have to use the files[] array.

{
    "autoload": {
        "classmap": ["src/", "lib/", "Something.php"]
    }
}


来源:https://stackoverflow.com/questions/26174024/composer-autoload-multiple-files-in-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!