Search code examples
phpcomposer-phpautoload

How to autoload helper functions as needed in Composer?


Say you have 1 file per function:

/src/Helpers/fooHelper.php

<?php

namespace MyHelper;

function fooHelper() {};

/src/Helpers/barHelper.php

<?php

namespace MyHelper;

function barHelper() {};

I see that there is

"autoload": {
    "files": ["src/Helpers/functions.php"]
}

Is it possible to autoload these functions via Composer on demand instead of every request?


Solution

  • Is it possible to autoload these functions via Composer on demand instead of every request?

    No, there is no autoloading support for functions in PHP. You need to either load them manually or add files with functions declaration to autoload.files config in composer.json - they're will be loaded on each request, even if you never use it.

    The only sane workaround at this moment is to wrap helpers in some static class, which could be autoloaded without any trouble.

    class MyHelper {
    
        public static function fooHelper() {}
    
        public static function barHelper() {}
    }
    
    MyHelper::fooHelper();
    MyHelper::barHelper();