Composer/PSR - How to autoload functions?

孤人 提交于 2019-11-28 08:52:49
mpen

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

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

(thanks Kint)

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!"
?>
  1. Add autoload info in composer.json
{
    "autoload": {
        "psr-4": {
            "Vendor\\Namespace\\": "src/"
        }
    }
}
  1. Create a OwnFunctions.php with your functions in src/Functions folder
// recommend
// http://php.net/manual/en/control-structures.declare.php
declare(strict_types=1);

namespace Vendor\Namespace\Functions\OwnFunctions;

function magic(int $number): string {
    return strval($number);
}
  1. In your index.php require composer autoload
declare(strict_types=1);
require_once __DIR__ . '/vendor/autoload.php';

use function Vendor\Namespace\Functions\OwnFunctions\magic;

echo magic(1);

// or you can use only OwnFunctions namespace
use Vendor\Namespace\Functions\OwnFunctions;

echo OwnFunctions\magic(1);

This also can be done with const

use const Vendor\Namespace\Functions\OwnFunctions\someConst;
echo someConst;

Official docs

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