PSR coding standards

October 26, 2013

I think cross-project, language wide coding standards like PSR are great. It makes reading or writing code from other projects easy. And since PSR is so widely adopted in the PHP programming scene, it’s a really good coding standard to adopt. When studying it, though, I came across two things that I really dislike in their standard. They both apply to PSR-2.

The eternal Spaces vs. Tabs debate

Indents are a really personal thing. Some people find 4 spaces a good indentation width, others prefer 2 spaces, even others prefer 8. That’s why tabs are so awesome, every good editor allows you to set your own tab width, so that your indentation is perfect for you in your editor, and perfect for somebody else in his or her editor of choice. Now, i’m really talking about indentation, not alignment. Allignment SHOULD be done using spaces. Things will still align, even if the tab with is changed. This is perfect in every case.

An example. . are spaces, and thus fixed width spacing. - stands for one space width inside a tab in a certain editor.

One tab is 2 spaces wide

class.ClassName {

One tab is 4 spaces wide


As you can see in these two examples, things keep aligning perfectly, everyone gets to use their own prefered indentation width, *and* your git history is as clean as using only spaces. When used consistently this method has all the upsides of the PSR-2 “only spaces” rule, and none of the downsides.

Curly brackets

PSR is not really consistent in this case. Control structures like if, elseif, switch, for and while must have their opening brackets on the same line, while functions, methods and classes must have their opening brackets on the next line.
I think it would be more consistent if control structures, functions, methods and classes would all have the same notation with brackets on the same line, like in this example:

namespace Vendor\Package;

class ClassName {
    public function fooBar($argument1, $argument2 = null) {
        if ($argument1 === $argument2) {
            // Return Foo
        else {
            // Return Bar

Also notice in the above example that every closing bracket is on its own line, unlike the PSR-2 standard way of putting the if closing bracket on the same line as the else statement, like this:

if ($argument1 === $argument2) {
    // Return Foo
} else {
    // Return Bar

I think this is inconsistent, and doesn’t help for readability.

That’s all…


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: