Coding Standards

Coding Standards

Symfony code is contributed by thousands of developers around the world. To make every piece of code look and feel familiar, Symfony defines some coding standards that all contributions must follow.

These Symfony coding standards are based on the PSR-1, PSR-2, PSR-4 and PSR-12 standards, so you may already know most of them.

Making your Code Follow the Coding Standards

Instead of reviewing your code manually, Symfony makes it simple to ensure that your contributed code matches the expected code syntax. First, install the PHP CS Fixer tool and then, run this command to fix any problem:

  1. $ cd your-project/
  2. $ php php-cs-fixer.phar fix -v

If you forget to run this command and make a pull request with any syntax issue, our automated tools will warn you about that and will provide the solution.

Symfony Coding Standards in Detail

If you want to learn about the Symfony coding standards in detail, here’s a short example containing most features described below:

  1. /*
  2. * This file is part of the Symfony package.
  3. *
  4. * (c) Fabien Potencier <[email protected]>
  5. *
  6. * For the full copyright and license information, please view the LICENSE
  7. * file that was distributed with this source code.
  8. */
  9. namespace Acme;
  10. use Other\Qux;
  11. /**
  12. * Coding standards demonstration.
  13. */
  14. class FooBar
  15. {
  16. const SOME_CONST = 42;
  17. /**
  18. * @var string
  19. */
  20. private $fooBar;
  21. private $qux;
  22. /**
  23. * @param string $dummy Some argument description
  24. */
  25. public function __construct($dummy, Qux $qux)
  26. {
  27. $this->fooBar = $this->transformText($dummy);
  28. $this->qux = $qux;
  29. }
  30. /**
  31. * @return string
  32. *
  33. * @deprecated
  34. */
  35. public function someDeprecatedMethod()
  36. {
  37. @trigger_error(sprintf('The %s() method is deprecated since vendor-name/package-name 2.8 and will be removed in 3.0. Use Acme\Baz::someMethod() instead.', __METHOD__), E_USER_DEPRECATED);
  38. return Baz::someMethod();
  39. }
  40. /**
  41. * Transforms the input given as first argument.
  42. *
  43. * @param bool|string $dummy Some argument description
  44. * @param array $options An options collection to be used within the transformation
  45. *
  46. * @return string|null The transformed input
  47. *
  48. * @throws \RuntimeException When an invalid option is provided
  49. */
  50. private function transformText($dummy, array $options = [])
  51. {
  52. $defaultOptions = [
  53. 'some_default' => 'values',
  54. 'another_default' => 'more values',
  55. ];
  56. foreach ($options as $name => $value) {
  57. if (!array_key_exists($name, $defaultOptions)) {
  58. throw new \RuntimeException(sprintf('Unrecognized option "%s"', $name));
  59. }
  60. }
  61. $mergedOptions = array_merge(
  62. $defaultOptions,
  63. $options
  64. );
  65. if (true === $dummy) {
  66. return 'something';
  67. }
  68. if (is_string($dummy)) {
  69. if ('values' === $mergedOptions['some_default']) {
  70. return substr($dummy, 0, 5);
  71. }
  72. return ucwords($dummy);
  73. }
  74. return null;
  75. }
  76. /**
  77. * Performs some basic operations for a given value.
  78. *
  79. * @param mixed $value Some value to operate against
  80. * @param bool $theSwitch Some switch to control the method's flow
  81. */
  82. private function performOperations($value = null, $theSwitch = false)
  83. {
  84. if (!$theSwitch) {
  85. return;
  86. }
  87. $this->qux->doFoo($value);
  88. $this->qux->doBar($value);
  89. }
  90. }

Structure

  • Add a single space after each comma delimiter;
  • Add a single space around binary operators (==, &&, …), with the exception of the concatenation (.) operator;
  • Place unary operators (!, --, …) adjacent to the affected variable;
  • Always use identical comparison unless you need type juggling;
  • Use Yoda conditions when checking a variable against an expression to avoid an accidental assignment inside the condition statement (this applies to ==, !=, ===, and !==);
  • Add a comma after each array item in a multi-line array, even after the last one;
  • Add a blank line before return statements, unless the return is alone inside a statement-group (like an if statement);
  • Use return null; when a function explicitly returns null values and use return; when the function returns void values;
  • Use braces to indicate control structure body regardless of the number of statements it contains;
  • Define one class per file - this does not apply to private helper classes that are not intended to be instantiated from the outside and thus are not concerned by the PSR-0 and PSR-4 autoload standards;
  • Declare the class inheritance and all the implemented interfaces on the same line as the class name;
  • Declare class properties before methods;
  • Declare public methods first, then protected ones and finally private ones. The exceptions to this rule are the class constructor and the setUp() and tearDown() methods of PHPUnit tests, which must always be the first methods to increase readability;
  • Declare all the arguments on the same line as the method/function name, no matter how many arguments there are;
  • Use parentheses when instantiating classes regardless of the number of arguments the constructor has;
  • Exception and error message strings must be concatenated using [sprintf](https://www.php.net/manual/en/function.sprintf.php "sprintf");
  • Calls to [trigger_error](https://www.php.net/manual/en/function.trigger-error.php "trigger_error") with type E_USER_DEPRECATED must be switched to opt-in via @ operator. Read more at Deprecating Code;
  • Do not use else, elseif, break after if and case conditions which return or throw something;
  • Do not use spaces around [ offset accessor and before ] offset accessor;
  • Add a use statement for every class that is not part of the global namespace;
  • When PHPDoc tags like @param or @return include null and other types, always place null at the end of the list of types.

Naming Conventions

  • Use camelCase for PHP variables, function and method names, arguments (e.g. $acceptableContentTypes, hasSession());
  • Use snake_case for configuration parameters and Twig template variables (e.g. framework.csrf_protection, http_status_code);
  • Use namespaces for all PHP classes and UpperCamelCase for their names (e.g. ConsoleLogger);
  • Prefix all abstract classes with Abstract except PHPUnit *TestCase. Please note some early Symfony classes do not follow this convention and have not been renamed for backward compatibility reasons. However, all new abstract classes must follow this naming convention;
  • Suffix interfaces with Interface;
  • Suffix traits with Trait;
  • Suffix exceptions with Exception;
  • Use UpperCamelCase for naming PHP files (e.g. EnvVarProcessor.php) and snake case for naming Twig templates and web assets (section_layout.html.twig, index.scss);
  • For type-hinting in PHPDocs and casting, use bool (instead of boolean or Boolean), int (instead of integer), float (instead of double or real);
  • Don’t forget to look at the more verbose Conventions document for more subjective naming considerations.

Service Naming Conventions

  • A service name must be the same as the fully qualified class name (FQCN) of its class (e.g. App\EventSubscriber\UserSubscriber);
  • If there are multiple services for the same class, use the FQCN for the main service and use lowercase and underscored names for the rest of services. Optionally divide them in groups separated with dots (e.g. something.service_name, fos_user.something.service_name);
  • Use lowercase letters for parameter names (except when referring to environment variables with the %env(VARIABLE_NAME)% syntax);
  • Add class aliases for public services (e.g. alias Symfony\Component\Something\ClassName to something.service_name).

Documentation

  • Add PHPDoc blocks for all classes, methods, and functions (though you may be asked to remove PHPDoc that do not add value);
  • Group annotations together so that annotations of the same type immediately follow each other, and annotations of a different type are separated by a single blank line;
  • Omit the @return tag if the method does not return anything;
  • The @package and @subpackage annotations are not used;
  • Don’t inline PHPDoc blocks, even when they contain just one tag (e.g. don’t put /** {@inheritdoc} */ in a single line);
  • When adding a new class or when making significant changes to an existing class, an @author tag with personal contact information may be added, or expanded. Please note it is possible to have the personal contact information updated or removed per request to the core team.

License

  • Symfony is released under the MIT license, and the license block has to be present at the top of every PHP file, before the namespace.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.