A few tips on how to keep your PHP code style under control

4 min

read

How many times have you seen a code that seemed to be written in a rush? Multiple times, I believe. In some cases, it’s written by someone else, but pretty often your own creations, after some time, make you think “who the hell wrote this crap”? Keeping code clean ain’t easy and that’s why I’ve decided to present you some tools which can help you keep your PHP code clean.

Keeping code under control is one thing, but even worse is the fact that there are no universal standards of coding. Huge, open-source projects, frameworks and libraries apply their own programming standards. The problem has been noticed some time ago, and it led to the origins of  PHP Standards Recommendations (PSR). It’s the document made jointly by the authors of the most popular PHP projects. 

Even though the key recommendations (PSR-0 to PSR-4) have been acknowledged by the majority of the PHP community as a de facto standard, later attempts at unifying more common application elements often failed and so many people have left the project since, including the authors of such famous projects as Symfony, Laravel, Doctrine or Guzzle.

Developers also vary their standards of code quality and cleanliness. The lack of coding standards sanitization at the project level can lead to needless disputes during the Code Review.

Maintaining a fairly good code quality isn’t an easy task. Below, I’ll try to show you a few static code analysis tools, which might help you with that.

But what is static code analysis? 

It’s an action performed by tools designed to read the source code without actually running it. Performing such an analysis is usually a part of the Continuous Integration process. Static analysers allow programmers bounding and predicting the behavior of software without running it. They also simplify and help reviewers checking the code, according to the rule “what can be automated, should be automated”. 

The variety of static code analysis tools in the PHP community is quite huge. Some of those are:

  • PHP Code Style Fixer (PHP CS Fixer), 
  • PHP Code Sniffer (PHP_CodeSniffer), 
  • Easy Coding Standard (ECS), 
  • PHPStan, 
  • Psalm,
  • Phan, 
  • PHP Insights,
  • Rector.

In the next part of the article, I’ll present you three of my favourite code analysers, which I use in most of my projects: ECS, PHPStan, and Psalm. Why those in particular? Among many options those are the ones which are, in my opinion, the easiest to use and provide the most advantages. Why three and not just one? Because those tools complement each other. 

As I mentioned earlier, projects often have different, “stale” code writing styles. Programmers involved in the project also have their own habits. That’s why the configuration of the analysers has to be individualized for each project and should be saved in the repository of that project. To facilitate the configuration process, I’ll show you some elementary configuration files we use at The Software House.

Fix my code!

Before you start fixing your code, it’s worth learning a few rules, which can help you along the way.

  1. Commit the code before you run any command that changes the code and before making any changes in the configuration of the tool. Running it may result in the script ruining your code and the changes can be difficult to recover.
  2. Run tests after each code change to be sure that everything still works as expected.
  3. When configuring an analyser, it’s best to start with all available checkers and fixers. Then, you should exclude those you do not need or want to be executed. After all, you’ll end up with the highest fitting number of enhancements.
  4. It’s pointless to use IDE plugins for this task or even to add those scripts as pre-commit hooks. Using them distracts the programmer. Instead, it’s better to run the checks just before pushing your code to the repository and, crucially, in CI.
  5. If your code is very old, conflicts in Composer’s dependencies can arise. In such a case, the solution would be to install those tools in a separate directory, for example under ./ecs/composer.json

EasyCodingStandard – one tool to rule ‘em all!

ECS is a static code analyser made by Tomas Votruba and contributors. It’s able to fix most of your code flaws automatically. It contains rules from PHP Code Fixer, Code Sniffer, Slevomat and Simplify. Also, it greatly simplifies the configuration of thereof. Sounds too good to be true? Check it for yourself! 

Below, there is an exemplary ECS config which I use (with some customization) in most of my projects.

Alright, but you may ask “how to use it?” Below, you’ll find a few simple steps:

  1. Save the above code in the main project folder (in ecs.yaml file).
  2. Install ECS: composer require --dev symplify/easy-coding-standard
  3. Run the checker: vendor/bin/ecs check src (the command executes dry-run by default – it means that it checks the code, but won’t change it).
    PHP code output
  4. Check the proposed changes. If any of them don’t meet your requirements, delete the respective rules from the configuration file or add them to the “skip” section. You can also add exceptions to specific files here and return to step 3. 
  5. After reaching a satisfying result, let the program fix your code. For this purpose,  commit the changes and then execute the command from step 3. This time, you should do it around with the “fix” argument: vendor/bin/ecs check src --fixPHP code output
  6. Not everything can be fixed automatically. If something is left in output, modify the code manually until the command’s output becomes green.
  7. Execute the test and/or click through the application to check if it still works properly.
  8. If something went wrong during the process, you can revert the code state to the commit you made before the fix command.
  9. Done. 🙂

Doing this may greatly improve your code’s quality. But hey, we are not done yet! Let’s see what else you can improve by using some more tools.

PHPStan

PHPStan is another useful tool. Its configuration is simplified to the bare minimum – you choose one of the predefined levels. In addition to that, you can expand its capabilities using one of many extensions. The downside is that this analyser doesn’t have an automatic code fixing function. Here is an exemplary config:

Again, let’s answer the question: how to use it?

  1. Save the above code in the project’s main directory, in the phpstan.neon file.
  2. Install PHPStan: composer require --dev phpstan/phpstan
  3. Launch it: vendor/bin/phpstan analyse src
  4. Fix errors presented in the output.
  5. Execute tests and/or click through the application to check if it still works properly.
  6. Now, you can raise the level in configuration and then go back to step 3, up until you reach a satisfying effect. From my experience, most projects will stop at levels 3 to 5.
  7. Done. 🙂

Psalm

The last of the tools which I use on a daily basis is called Psalm. It was made by Vimeo. Unfortunately, just like PHPStan, your code won’t be fixed automatically. The configuration is done through an XML file and offers a lot of capabilities. My recommendation would be to begin with all the rules at the minimum level of “warning”, gradually excluding them. The final config would look like this.

How to use it?

  1. Save the above code in the project’s main directory, in the psalm.xml file.
  2. Install Psalm: composer require --dev vimeo/psalm 
  3. Launch it: vendor/bin/psalm --show-info=false
  4. If there are too many errors or you don’t agree with any of them, you should exclude the rules and files which you aren’t going to correct.
  5. Fix your code accordingly to the remaining rules.
  6. Execute the test and/or click through the application to check if it still works properly.
  7. Done. 🙂

If you are interested in seeing some real examples of the aforementioned tools, I’ll recommend you visiting our working example of those analysers on GitHub repository

What’s next?

Now, the code looks much cleaner! But wait, isn’t your brain satiated with this knowledge? Do you ask yourself questions: “Why are there so many of these tools? Why isn’t it enough to just use one of them? What ways do they differ in?”.

If so, then I’d like to recommend you some more detailed technical articles on the excellent blog made by Tomas Votruba, the creator of the aforementioned ECS, which will hopefully answer those questions:

Estimate your project





or contact us directly at [email protected]

Thanks

Thank you!

Your message has been sent. We’ll get back to you in 24 hours.

Back to page
24h

We’ll get back to you in 24 hours

to address your needs as quick as possible.

Estimation

We’ll prepare an estimation of the project

describing the team compostition, timeline and costs.

Code review

We’ll perform a free code review

if you already have an existing system or a part of it.

Our work was featured in:

Tech Crunch
Forbes
Business Insider

Aplikujesz do

The Software House

Aplikuj teraz

wyślij CV na adres: [email protected]

CopiedTekst skopiowany!

Nie zapomnij dodać klauzuli:

Kopiuj do schowka Copy

Jakie będą kolejne kroki?

Phone

Rozmowa telefoniczna

Krótka rozmowa o twoim doświadczeniu,
umiejętnościach i oczekiwaniach.

Test task

Zadanie testowe

Praktyczne zadanie sprawdzające dokładnie
poziom twoich umiejętności.

Meeting

Spotkanie w biurze

Rozmowa w biurze The Software House,
pozwalająca nam się lepiej poznać.

Response 200

Response 200

Ostateczna odpowiedź i propozycja
finansowa (w ciągu kilku dni od spotkania).

spinner