Composer/PSR - How to autoload functions?

22,949

Solution 1

You can autoload specific files by editing your composer.json file like this:

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

(thanks Kint)

Solution 2

After some tests, I have came to the conclusions that adding a namespace to a file that contains functions, and setting up composer to autoload this file seems to not load this function across all the files that require the autoload path.

To synthesize, this will autoload your function everywhere:

composer.json

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

src/greetings.php

<?php
    if( ! function_exists('greetings') ) {
        function greetings(string $firstname): string {
            return "Howdy $firstname!";
        }
    }
?>

...

But this will not load your function in every require of autoload:

composer.json

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

src/greetings.php

<?php
    namespace You;

    if( ! function_exists('greetings') ) {
        function greetings(string $firstname): string {
            return "Howdy $firstname!";
        }
    }
?>

And you would call your function using use function ...; like following:

example/example-1.php

<?php
    require( __DIR__ . '/../vendor/autoload.php' );

    use function You\greetings;

    greetings('Mark'); // "Howdy Mark!"
?>
Share:
22,949
mpen
Author by

mpen

Updated on March 15, 2020

Comments

  • mpen
    mpen about 4 years

    How can I autoload helper functions (outside of any class)? Can I specify in composer.json some kind of bootstrap file that should be loaded first?