PSR-4 directory structure and namespacing for a set of functions?

烈酒焚心 提交于 2019-12-07 04:05:26

问题


I have a set of PHP functions that I find useful. I want to create a PSR-4 compliant repository for them, but the guides I have found (1,2,3) seem to talk only about classes for autoloading.

For instance, my files are as follows, with one function per file:

my_cool_function1.php
my_cool_function2.php
... etc.

How can I create a PSR-4 compliant library from them?


回答1:


The reason you're not able to find any documentation for PSR-4 autoloading files which aren't classes, that's because as the specification states - it's designed for autoloading classes.

Taken directly from the official specs:

This PSR describes a specification for autoloading classes from file paths. It is fully interoperable, and can be used in addition to any other autoloading specification, including PSR-0. This PSR also describes where to place files that will be autoloaded according to the specification.

More specifically;

The term "class" refers to classes, interfaces, traits, and other similar structures.

A file with functions isn't really a similar structure.

To autoload those files, you'll need to autoload using files:

"autoload": {
    "files": [
        "src/my_cool_function1.php",
        "src/my_cool_function2.php"
    ],
    "psr-4": {
        "SomeNamespace\\": "src/YourNamespace/"
    }
}

You'll notice from this, that the psr-4 spec maps (usually) to a namespace.




回答2:


Don't forget you can use static functions in classes so that PSR-4 will load them

class MyClass {
    public static my_cool_function1() {}
}

Then you can invoke them as just a normal function using the colon operator:

MyClass::my_cool_function1() {}


来源:https://stackoverflow.com/questions/32443327/psr-4-directory-structure-and-namespacing-for-a-set-of-functions

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