PHP Composer PSR-4 Tutorial

In this post I will be walking you through how to setup a project using composer and PSR-4 autoloading

PSR-4 is a community standard relating to class autoloading. The reason it was developed was to standardize and map namespaces to physical directory structures. PSR-4 effectively removes the requirement to use the require*/include* keywords in your project.

Composer was initially developed to use the PSR-0 namespace standard (it has been replaced with PSR-4). Composer is used to manage your projects dependencies and act as a single source of truth for your project in that you will only ever need to include Class files from the Composer autoloader. Prior to Composer you would often see custom autoloaders in projects that would essentially go through and require all of it's own class files that it would need.

PSR-4

 \<NamespaceName>(\<SubNamespaceNames>)*\<ClassName>

What this means is that you should NOT pollute the global namespace with your classes. You should always define a namespace sometimes referred to as the vendor namespace. If we take a look at SlimPHP we see that we operate under the Slim vendor namespace. When we create a Slim App that is the class that we create \Slim\App.

In composer we tell composer that we are registering that namespace prefix and map it to a local folder.

    "autoload": {
        "psr-4": {
            "Slim\\": "Slim"
        }
    }

In this directive we tell Composer that any Class in the local Slim directory will have the Slim namespace prefix. So our class \Slim\App.php will have the namespace \Slim and will have a class name of App.

You can go down and down directories, each time creating a new SubNamespace, and finally the class at the end.

So this is valid class: \Om\Nom\Nom\Nom\Nom\Cookie

The autoload section however could look different depending where you set the prefix.

    "autoload": {
        "psr-4": {
            "Om\\": "src"
        }
    }, /* vs */
    "autoload": {
        "psr-4": {
            "Om\\Nom\\Nom\\": "src"
        }
    }

In the first Example your file will be located at: src/Nom/Nom/Nom/Nom/Cookie.php

While in the second example it will be located at: src/Nom/Nom/Cookie.php

Composer just adds the prefix found inside the autoload to all class files underneath the directory. This is very handy if you decide to version your Class files by using a sub-namespace like v1, v2, v3 ...etc.

Written by Glenn Eggleton on Monday October 2, 2017
Permalink - Chapter: php