Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

psr-4

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?

like image 382
user151841 Avatar asked Sep 07 '15 17:09

user151841


Video Answer


2 Answers

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.

like image 171
Amo Avatar answered Sep 19 '22 22:09

Amo


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() {}
like image 43
Jonathan Avatar answered Sep 17 '22 22:09

Jonathan