PHP specification – symfony code specification

Time:2021-9-20

Note: specifications are mainly fromSymfony Coding Standards, the example is added by myself. Please correct any errors.

Symfony’s coding specification is based onPSR-1, PSR-2 and PSR-4Based on.

tool

usephp-cs-fixerTools to automatically check coding specifications

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

structure

Add a space after each comma separator

$arr = [1, 2, 3];

Add a space to the left and right of all binary operators,.Except operator

$sum = $a + $b;
$name = $firstName.$lastName;

Unary operators are immediately followed by associated variables, and no spaces need to be added

if( !$name )

Always use congruence unless you need to do some type juggling

if($rst === true)

use==!====, and!==When making judgment, you need to put the constant amount on the left to avoid accidents

if(10 === $number)

The last item in a multiline array is always parenthesized

$arr = [
    [1,2],
    [1,2],
];

Except in code blockreturnStatement, thenreturnLeave an empty line before the statement

//Add empty line

althoughreturn;Andreturn nullThere is no difference in grammar. However, the use should be based on specific scenarios: if the function does not need to return a value, usereturn;If a return value is required, but the return value isnull, usereturn null

function foo() : void
{
    return;
}

Control statements cannot omit curly braces

if($a === 1){
    return true;
}

A file contains only one class. Except for private help classes that do not need to be instantiated externally.

Write the inheritance of the class and the interface declaration of the implementation on the same line.

class User extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract

Property must be declared before the method

class Foo
{
    private $bar;

    public function foo()
    {

    }
}

Methods are ranked from high to low accessibility by default. In addition, constructors__construct. test methodsetUp()tearDown()Always put first to improve readability

public foo() {}
protected bar() {}
private barz() {}

No matter how many parameters are included in the method, they should be declared on the same line

public function __construct($command, string $cwd = null, array $env = null, $input = null, ?float $timeout = 60)
{

}

Class instantiation always uses parentheses

$foo = new Foo();

Exception and error message strings must usesprintfTo splice;

throw new CommandNotFoundException(sprintf('Command "%s" does not exist.', $name));

When the error type isE_USER_DEPRECATEDYou need to add@

@trigger_error("foo", E_USER_DEPRECATED);

There should be no spaces between array accessors

$arr[0][1];

If the referenced class does not belong to the global namespace, each class needs to useuse

use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\LogicException;

Note in document@paramor@returnIf includednullType, tonullPut it at the back

/**
 * @param int|null
 * @return string|null
 */

Naming convention

Use camel case to name variables, methods, or functions

$acceptableContentTypes
hasSession();

Use snake_case nomenclature to name configuration parameters andTwigTemplate variable

framework.csrf_protection
http_status_code

Add namespaces for all classes. Class names always use uppercase camel case

<?php

namespace App;

class FooBar {

}

Abstract class additionabstractPrefix, except phpunit’s testcase abstract class.

abstract class Helper 
{

}

Interface additionInterfacesuffix

interface ExceptionInterface
{
}

Trail addTraitsuffix

trait FooTrait
{
}

Exception additionExceptionsuffix

class CommandNotFoundException 
{

}

Use uppercase humps to name PHP files and lowercase serpents to name template engines or web resource files

FooBar.php
section_layout.html.twig
index.scss

In document comments or type conversion, useboolinstead ofbooleanorBoolean, useintinstead ofinteger, usefloatinstead ofdoubleorreal

(int) $a;
(bool) $a;
(float) $a;

service

This part mainly introducessymfonyFramedservicesUsage specification

  • The name of the service uses the fully qualified name of the class, such asApp\EventSubscriber\UserSubscriber;
  • When there are multiple services with the same name, the main service is named with a fully qualified name, and the other services are named with lowercase underscores. It can also be used.Group symbols, for examplesomething.service_name, fos_user.something.service_name;
  • Parameter names are in lowercase and environment variable names are in lowercase%env(VARIABLE_NAME)%
  • Add class associations to public services, such as associationsSymfony\Component\Something\ClassNamebysomething.service_name

file

Add for all classes, methods, and functionsPHPDocnotes.

Group according to types, with a blank line between different types

/**
 * @FooBar(1)
 * @FooBar(2)
 *
 * @var int
 */
private $var;

If there is no return value, omit@returnnotes

/**
 * Configures the current command.
 */
protected function configure()
{
}

Do not use@packageand@subpackageMark.

Even if there is only one label, do not write it on the same line, such as/** {@inheritdoc} */

/**
 * @inheritdoc
 */
function testInheritDocValid1($test)
{
}

When you add a new class or make a lot of changes to an existing class, you may want to add one@authorMark to leave personal contact information.

/**
 * @author Jérôme Tamarelle <[email protected]>
 */

Example

Official examples

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <[email protected]>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Acme;

/**
 * Coding standards demonstration.
 */
class FooBar
{
    const SOME_CONST = 42;

    /**
     * @var string
     */
    private $fooBar;

    /**
     * @param string $dummy Some argument description
     */
    public function __construct($dummy)
    {
        $this->fooBar = $this->transformText($dummy);
    }

    /**
     * @return string
     *
     * @deprecated
     */
    public function someDeprecatedMethod()
    {
        @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);

        return Baz::someMethod();
    }

    /**
     * Transforms the input given as first argument.
     *
     * @param bool|string $dummy   Some argument description
     * @param array       $options An options collection to be used within the transformation
     *
     * @return string|null The transformed input
     *
     * @throws \RuntimeException When an invalid option is provided
     */
    private function transformText($dummy, array $options = [])
    {
        $defaultOptions = [
            'some_default' => 'values',
            'another_default' => 'more values',
        ];

        foreach ($options as $option) {
            if (!in_array($option, $defaultOptions)) {
                throw new \RuntimeException(sprintf('Unrecognized option "%s"', $option));
            }
        }

        $mergedOptions = array_merge(
            $defaultOptions,
            $options
        );

        if (true === $dummy) {
            return null;
        }

        if ('string' === $dummy) {
            if ('values' === $mergedOptions['some_default']) {
                return substr($dummy, 0, 5);
            }

            return ucwords($dummy);
        }
    }

    /**
     * Performs some basic check for a given value.
     *
     * @param mixed $value     Some value to check against
     * @param bool  $theSwitch Some switch to control the method's flow
     *
     * @return bool|void The resultant check if $theSwitch isn't false, void otherwise
     */
    private function reverseBoolean($value = null, $theSwitch = false)
    {
        if (!$theSwitch) {
            return;
        }

        return !$value;
    }
}

This work adoptsCC agreement, reprint must indicate the author and the link to this article