Tooling PHP Best practices
This section list a number of tools that will help you respecting the best practices.
Use a static analysis tool
A static analysis tool can automatically analyze your code base and issue warnings on potential bugs. Unlike styling tools (like PHP-CS-Fixer), the static analysis tools actually understand your code by creating a tree like representation of all your classes. They can go deep in your code, understand the type of each variable and provide advanced reports.
At TheCodingMachine, we are the proud sponsors of PHPStan. We even went as far as designing an extension for PHPStan that actually checks some of the rules described in this very web site.
Psalm is also known to be a very good static analysis tool and is especially great at checking types. It comes with its own generics syntax.
Use unit/integration tests
Unit / integration tests are a great way to test your program automatically.
A whole book could be written on unit tests so rather than writing too few, here is a link to best practices from PHPUnit
Use Continuous Integration
You should never trust you running your tools manually. If you have no automated way to run your tools, here is what will happen:
- At some point in your project, you will have a rush
- You will commit to your repository without running your tools
- After some time, the effort to bring back your code to a correct state will take too much effort
- You will end up abandoning the tools
Each of your changes should be written to a branch. When you open a pull-request on that branch, the CI server will automatically run the tools for you and notify you of any problem.
Note: of course, you should run the tests locally first. It is way faster to run the tests locally that to wait for the CI server to kick in and run the tests. The CI server is only here as a last resort.
There are many CI tools out there. At TheCodingMachine, we use Gitlab CI that is directly integrated to Gitlab. But there are many other tools like Travis (with a generous free plan for open-source projects), Jenkins...
Use static code analyzers in your IDE
This extension adds a great number of checks to help you write high quality PHP code. Some of the checks are redundant with PHPStan, but you get the chance to view those directly in your IDE while coding.
Found a typo? Something is wrong in this documentation? Just fork and edit it!