发布于 2015-08-27 16:48:41 | 226 次阅读 | 评论: 0 | 来源: 网络整理
When contributing code to Symfony, you must follow its coding standards. To make a long story short, here is the golden rule: Imitate the existing Symfony code. Most open-source Bundles and libraries used by Symfony also follow the same guidelines, and you should too.
Remember that the main advantage of standards is that every piece of code looks and feels familiar, it’s not about this or that being more readable.
Symfony follows the standards defined in the PSR-0, PSR-1 and PSR-2 documents.
Since a picture - or some code - is worth a thousand words, here’s a short example containing most features described below:
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* 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;
private $fooBar;
/**
* @param string $dummy Some argument description
*/
public function __construct($dummy)
{
$this->fooBar = $this->transformText($dummy);
}
/**
* @param string $dummy Some argument description
* @param array $options
*
* @return string|null Transformed input
*
* @throws RuntimeException
*/
private function transformText($dummy, array $options = array())
{
$mergedOptions = array_merge(
array(
'some_default' => 'values',
'another_default' => 'more values',
),
$options
);
if (true === $dummy) {
return;
}
if ('string' === $dummy) {
if ('values' === $mergedOptions['some_default']) {
return substr($dummy, 0, 5);
}
return ucwords($dummy);
}
throw new RuntimeException(sprintf('Unrecognized dummy option "%s"', $dummy));
}
private function reverseBoolean($value = null, $theSwitch = false)
{
if (!$theSwitch) {
return;
}
return !$value;
}
}
==
, &&
, ...), with
the exception of the concatenation (.
) operator;!
, --
, ...) adjacent to the affected variable;return
statements, unless the return is alone
inside a statement-group (like an if
statement);setUp
and
tearDown
methods of PHPUnit tests, which should always be the first methods
to increase readability;sprintf
.Abstract
. 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;Interface
;Trait
;Exception
;bool
(instead of boolean
or Boolean
), int
(instead of integer
), float
(instead of
double
or real
);fos_user
);SERVICE NAME.class
convention.@return
tag if the method does not return anything;@package
and @subpackage
annotations are not used.