loading...

Coding standards in PHP using PHP-CS-Fixer

purplebooth profile image Billie ・3 min read

One of the best things you can do early on in your project is define a coding standard.

This has a number of benefits:

  • Standard inline documentation
  • No indentation conflicts when editing others code
  • Reduced cognitive overhead when switching files and code blocks
  • Less time talking about coding standards
  • Enable static analysis of code based on inline documentation

Now in PHP we are very lucky to have an organisation that defines sensible standards for code, the FIG (or Framework Interoperability Group). These come in the form of PSR-1 and PSR-2. These standards are pretty loose but all of the major frameworks use them, but it's worth making sure the standard you choose does too.

When choosing a coding standard if you have framework or library you use a lot, then you should consider having a coding standard that matches it. By doing this the "other" code that you come into contact with most. This has the added benefit that if you get a new team member they're going to feel at home with the similar style to code they have seen before.

Also this gives you a direct way to defuse arguments about X styling trait, pass on the blame to the library you are taking your style from.

The next important thing to bare in mind is no one will follow your standard if you can't automatically fix your code to it. If you mildly disagree with the indentation or styling of code it's easy to gloss over that if it's automatically fixed just before you commit, but if you have to go through each instance and fix them manually, people will get pissed off. Ultimately unhappy developers don't do things that they don't want to - especially easy to be missed things like a coding standard.

To this end I would recommend using php-cs-fixer. PHP-CS-Fixer is a PHP tool that will help you fix your PHP code to follow, by automatically fixing the problems with coding style in your codebase.

You can run it in a couple of ways. Firstly just standalone using someone elses standard.

php-cs-fixer fix /path/to/project --rules=@Symfony

Would fix your project to Symfony stanard.

You can even add extra fixers too

php-cs-fixer fix /path/to/project --rules=@Symfony,ordered_class_elements

Would fix your project to Symfony standard, and include the ordered_class_elements fixer, that orders the elements in a class.

Getting each developer to remember what flags to pass for a project could be tricky though, so you can save this in a .php_cs.dist file with your standard in.

This is a copy of what my standard looks like.

<?php

return PhpCsFixer\Config::create()
                        ->setRiskyAllowed(true)
                        ->setRules(
                            [
                                '@Symfony' => true,
                                '@Symfony:risky' => true,
                                '@PHP71Migration' => true,
                                'array_syntax' => ['syntax' => 'short'],
                                'dir_constant' => true,
                                'heredoc_to_nowdoc' => true,
                                'linebreak_after_opening_tag' => true,
                                'modernize_types_casting' => true,
                                'no_multiline_whitespace_before_semicolons' => true,
                                'no_unreachable_default_argument_value' => true,
                                'no_useless_else' => true,
                                'no_useless_return' => true,
                                'ordered_class_elements' => true,
                                'ordered_imports' => true,
                                'phpdoc_add_missing_param_annotation' => ['only_untyped' => false],
                                'phpdoc_order' => true,
                                'declare_strict_types' => true,
                                'doctrine_annotation_braces' => true,
                                'doctrine_annotation_indentation' => true,
                                'doctrine_annotation_spaces' => true,
                                'psr4' => true,
                                'no_php4_constructor' => true,
                                'no_short_echo_tag' => true,
                                'semicolon_after_instruction' => true,
                                'align_multiline_comment' => true,
                                'doctrine_annotation_array_assignment' => true,
                                'general_phpdoc_annotation_remove' => ['annotations' => ["author", "package"]],
                                'list_syntax' => ["syntax" => "short"],
                                'phpdoc_types_order' => ['null_adjustment'=> 'always_last'],
                                'single_line_comment_style' => true,
                            ]
                        )
                        ->setCacheFile(__DIR__.'/.php_cs.cache')
                        ->setFinder(
                            PhpCsFixer\Finder::create()
                                             ->in(__DIR__)
                        );

This file is hands in other ways. You can also tell php-cs-fixer to skip certain files.

See this finder line

          ->setFinder(
                            PhpCsFixer\Finder::create()
                                             ->in(__DIR__)
                        );

You ignore files by adding this

          ->setFinder(
                            PhpCsFixer\Finder::create()
                                             ->in(__DIR__)
                                             ->notPath('/^app\/check.php/')
                                             ->notPath('/^web\/config.php/')

                        );

You can find a full guide on everything you can do with php-cs-fixer here. But hopefully this is enough to get you started using a tool that is super useful for all PHP projects.

Posted on by:

purplebooth profile

Billie

@purplebooth

I write PHP but other things when I am at home/I also have curly hair.

Discussion

pic
Editor guide
 

I installed the php-cs-fixer extension on vscode. But when I save the file I get this error.

PHP CS Fixer: php general error.

Extesion: marketplace.visualstudio.com/items...

I am using Ubuntu 18.04
PATH: /usr/local/bin/php-cs-fixer

PHP CS Fixer 2.15.3 Europe Round by Fabien Potencier and Dariusz Ruminski (705490b)

Do you know why?