Please follow PSR-2 from the PHP-Fig

Posted by Andy Huggins on May 02, 2016

Basically, coding style is about as dry a subject as you can get. 

"The code works, style doesn't matter" is a thought I used to think myself. But as I have written more code and jumped on more projects, the first thing we, as developers, tend to do, is open up the code and start reading it to see how things work.

Do this a few times on a few different projects and those little details of whether or not your control structures (if, foreach, for) opening curly brace are on the same line or the next line, end up affecting how easily you can consume code. Change up enough of those (what seem like insignificant) details and it's enough to jar your brain.

This is why it is important to have a coding style.

Now, having one on a project is good, but really, that's only good when you are bouncing around in your own project. What happens when you move to a new job or start to help a friend on a project? You kind of have to relearn a new style. This is kind of crappy, and the annoying thing is, we do it to ourselves.

So if we all as developers adopted a standard and used it in our projects every time. It would be easier for new developers to jump in and help out.

Luckily the PHP-FIG has already set a standard for just this very thing. 

The PHP-FIG (Framework Interop Group) is a group that aims to make packages framework agnostic, as in a package should be able to be used in Laravel, FuelPHP, Symfony or any other framework. In order to achieve that, they set some standards so that developers can expect things to work a certain way. Think of it like this, if you make a screwdriver, it doesn't do you any good if yours has square head when all the screws have a cross pattern. The square wouldn't be able to fit, and the screwdriver is then useless except for screws that accept square screwdrivers.

The recommendation for coding style is referred to as PSR-2, (PSR stands for PHP Standard Recommendation). If you read over the guidelines, it's actually pretty simple. Don't like that? But want to adhere to PSR-2, then set up your editor of choice with a PSR-2 code linter and your editor will automatically alert you when you are not adhering to the standard. Additionally, there are some things that will automatically format your code for you, so each time you save your file, it will conform to PSR-2.

I hope you follow PSR-2 going forward or at least consider it. Once you get used to the style it does become easier to scan code. Which is a benefit for everyone working on a project with you.

How to Enforce PSR-2 in PHPStorm

Laracasts shows you how to do this