Composer Autoload Multiple Files in Folder

后端 未结 2 921
醉梦人生
醉梦人生 2021-02-07 01:54

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

\"require\": {
    ...
},
\"require-dev\": {
    ...
},
\"autoload\": {
    \"psr-4\":         


        
2条回答
  •  独厮守ぢ
    2021-02-07 02:04

    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.

提交回复
热议问题