Practical Guide To PSR-0 and PSR-4

When the PHP Framework Interoperability Group (FIG) came out with a second recommendation for autoloading code without deprecating the first it caused some confusion. Should I use PSR-4, the new recommendation, or keep using PSR-0? What was the practical difference? Was PSR-4 just for the case where I wanted to use the new features?

The practical path forward wasn’t clear and when I started asking around I found differing opinions.

After talking with numerous people including gaining a little (official?) guidance from Larry Garfield and looking into some usage issues, here is my take on some practical guidance.

1. Use PSR-4 For All New Projects

This may seem like a no brainer. If you’re starting a new codebase use PSR-4. Even if you’re going to use the same directory structure that you would have done in PSR-0. Though, there is likely a case where you can drop at least one directory.

2. Use a PSR-0/4 Loader

If you’re using composer there is already support for both PSR-4 and PSR-0. You can use projects using either recommendation side by side.

Other loaders, such as the Symfony CLassLoader, already support PSR-4 as well. At this point there isn’t usually a good reason to use your own loader.

3. As Time Allows, Migrate to PSR-4

When you have time, such as when you already working on a codebase, migrate to PSR-4. Unless you’re using the older style PEAR separator (Foo_Bar_Baz) there is almost not work involved.

Lets take a look at a Composer example. Using PSR-0 you might have something like:

{
    "name": "foo/bar",
    "autoload": {
        "PSR-0": {
            "Foo": "src"
        }
    }
}

This could be converted to a PSR-4 format of:

{
    "name": "foo/bar",
    "autoload": {
        "PSR-4": {
            "Foo\\": "src/Foo"
        }
    }
}

But, why would this change matter besides using the shiny new recommendation? This was the question I had.

The real difference is that PSR-4 doesn’t handle the Foo_Bar_Baz case and you can remove some directories in your project to make the layout simpler. And, it’s the latest recommendation on the issue.

This is why I noted “As Time Allows” for making the change. If you’re in the code, make the change to the latest recommendation. If you’re not, then you don’t need to be in any hurry.