PSR-1, PSR-2, CS-Fixer
Nguyen Tien Si
GO1
Agenda
- PSR-1
- PSR-2
- CS-Fixer
PSR-1, 2?
PSR: PHP Standard Recommendation
PSR-1: Basic Coding Standard
PSR-2: Coding Style Guide
PSR-1
-
Files MUST use only <?php and <?= tags.
-
Files MUST use only UTF-8 without BOM for PHP code.
-
Files SHOULD either declare symbols (classes, functions, constants, etc.) or cause side-effects (e.g. generate output, change .ini settings, etc.) but SHOULD NOT do both.
-
Namespaces and classes MUST follow an "autoloading" PSR: [PSR-0, PSR-4].
-
Class names MUST be declared in StudlyCaps.
-
Class constants MUST be declared in all upper case with underscore separators.
-
Method names MUST be declared in camelCase.
PSR-2
- Code MUST follow a "coding style guide" PSR [PSR-1].
- Code MUST use 4 spaces for indenting, not tabs.
- There MUST NOT be a hard limit on line length; the soft limit MUST be 120 characters; lines SHOULD be 80 characters or less.
- There MUST be one blank line after the namespace declaration, and there MUST be one blank line after the block of use declarations.
- Opening braces for classes MUST go on the next line, and closing braces MUST go on the next line after the body.
- ...
Why we need standard?

Why have a coding standard?
- Improved code maintainability.
- Improved code quality.
- Improved development speed.
- Better teamwork.
- Make it quicker and easier for a developer to move to a different project or team.
- Fewer bugs.
- The coding standard should be a living document.
CS-Fixer
Install
[23:26][mrsinguyen@Nguyen:~/Tools]$ wget http://get.sensiolabs.org/php-cs-fixer.phar -O php-cs-fixer
[23:26][mrsinguyen@Nguyen:~/Tools]$ chmod a+x php-cs-fixer
[23:26][mrsinguyen@Nguyen:~/Tools]$ sudo mv php-cs-fixer /usr/local/bin/php-cs-fixer
[23:26][mrsinguyen@Nguyen:~/Tools]$ php-cs-fixer
PHP CS Fixer version 1.2 by Fabien Potencier (7aa4cff)
Usage:
[options] command [arguments]
Options:
--help (-h) Display this help message.
--quiet (-q) Do not output any message.
--verbose (-v|vv|vvv) Increase the verbosity of messages: 1
for normal output, 2 for more verbose output and 3 for debug.
--version (-V) Display this application version.
--ansi Force ANSI output.
--no-ansi Disable ANSI output.
--no-interaction (-n) Do not ask any interactive question.Demo
[16:58][mrsinguyen@Nguyen:~/Tools]$ php-cs-fixer fix foo.php --diff
1) /Users/mrsinguyen/Tools/foo.php
---------- begin diff ----------
--- Original
+++ New
@@ @@
-<? function a_b_c()
-{ $a=1;
- $b=2;
- return $a+b;
+<?php function a_b_c()
+{
+ $a = 1;
+ $b = 2;
+
+ return $a+b;
}
---------- end diff ----------
Fixed all files in 0.188 seconds, 4.250 MB memory used
References
- http://cs.sensiolabs.org
- http://www.php-fig.org
Question?
PSR-1, PSR-2, CS-Fixer
By Nguyen Tien Si
PSR-1, PSR-2, CS-Fixer
- 1,247