问题
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