code_style.md 7.31 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
Yii2 code standard
==================

This code standard is used for all the Yii2 core classes and can be applied to
your application in order to achieve consistency among your team. Also it will
help in case you want to opensource code.

PHP file formatting
-------------------

### General

13 14
- Do not end file with `?>` if it contains PHP code only.
- Do not use `<?`. Use `<?php` instead.
15
- Files should be encoded in UTF-8.
16 17
- Any file that contains PHP code should end with the extension `.php`.
- Do not add trailing spaces to the end of the lines.
18

19
#### Indentation
20

21
All code must be indented with tabs. That includes both PHP and JavaScript code.
22

23
#### Maximum Line Length
24 25 26 27

We're not strictly limiting maximum line length but sticking to 80 characters
where possible.

28 29 30 31
### PHP types

All PHP types and values should be used lowercase. That includes `true`, `false`,
`null` and `array`.
32

33
### Strings
Alexander Makarov committed
34

35
- If string doesn't contain variables or single quotes, use single quotes.
Alexander Makarov committed
36

37 38 39
~~~
$str = 'Like this.';
~~~
40

41 42
- If string contains single quotes you can use double quotes to avoid extra escaping.
- You can use the following forms of variable substitution:
Alexander Makarov committed
43

44
~~~
45 46 47 48 49 50 51 52 53 54 55 56
$str1 = "Hello $username!";
$str2 = "Hello {$username}!";
~~~

The following is not permitted:

~~~
$str3 = "Hello ${username}!";
~~~

### String concatenation

57
Add spaces around dot when concatenating strings:
58 59

~~~
60
$name = 'Yii' . ' Framework';
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
~~~

When string is long format is the following:

~~~
$sql = "SELECT *"
     . "FROM `post` "
     . "WHERE `id` = 121 ";
~~~


### Numerically indexed arrays

- Do not use negative numbers as array indexes.

Use the following formatting when declaring array:

~~~
$arr = array(3, 14, 15, 'Yii', 'Framework');
~~~

If there are too many elements for a single line:

~~~
$arr = array(
	3, 14, 15,
	92, 6, $test,
	'Yii', 'Framework',
);
~~~

### Associative arrays

Use the following format for associative arrays:

~~~
$config = array(
	'name'  => 'Yii',
	'options' => array(
		'usePHP' => true,
	),
);
~~~

### Classes

- Classes should be named using `CamelCase`.
- The brace should always be written on the line underneath the class name.
- Every class must have a documentation block that conforms to the PHPDoc.
110 111
- All code in a class must be indented with a single tab.
- There should be only one class in a single PHP file.
112 113
- All classes should be namespaced.
- Class name should match file name. Class namespace should match directory structure.
114 115 116 117 118 119

~~~
/**
 * Documentation
 */
class MyClass extends \yii\Object implements MyInterface
120
{
121
	// code
122 123 124
}
~~~

125 126 127 128 129 130 131 132 133 134 135 136

### Class members and variables

- When declaring public class members specify `public` keyword explicitly.
- Variables should be declared at the top of the class before any method declarations.
- Private and protected variables should be named like `$_varName`.
- Public class members and standalone variables should be named using `$camelCase`
  with first letter lowercase.
- Use descriptive names. Variables such as `$i` and `$j` are better not to be used.

### Constants

Qiang Xue committed
137
Both class level constants and global constants should be named in uppercase. Words
138 139 140 141 142 143 144 145 146
are separated by underscore.

~~~
class User {
	const STATUS_ACTIVE = 1;
	const STATUS_BANNED = 2;
}
~~~

Qiang Xue committed
147
It's preferable to define class level constants rather than global ones.
148

149 150 151
### Functions and methods

- Functions and methods should be named using `camelCase` with first letter lowercase.
152
- Name should be descriptive by itself indicating the purpose of the function.
153
- Class methods should always declare visibility using `private`, `protected` and
154
  `public` modifiers. `var` is not allowed.
155
- Opening brace of a function should be on the line after the function declaration.
156

157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
~~~
/**
 * Documentation
 */
class Foo
{
	/**
	 * Documentation
	 */
	public function bar()
	{
		// code
		return $value;
	}
}
~~~
Qiang Xue committed
173

174
Use type hinting where possible:
175 176 177 178 179 180 181 182

~~~
public function __construct(CDbConnection $connection)
{
	$this->connection = $connection;
}
~~~

183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
### Function and method calls

~~~
doIt(2, 3);

doIt(array(
	'a' => 'b',
));

doIt('a', array(
	'a' => 'b',
));
~~~

### Control statements

- Control statement condition must have single space before and after parenthesis.
- Operators inside of parenthesis should be separated by spaces.
- Opening brace is on the same line.
- Closing brace is on a new line.
Qiang Xue committed
203
- Always use braces for single line statements.
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222

~~~
if ($event === null) {
	return new Event($this);
} elseif ($event instanceof CoolEvent) {
	return $event->instance();
} else {
	return null;
}

// the following is NOT allowed:
if(!$model)
	throw new Exception('test');
~~~


### Switch

Use the following formatting for switch:
223 224

~~~
225 226 227
switch ($this->phpType) {
	case 'string':
		$a = (string)$value;
Alexander Makarov committed
228
		break;
229
	case 'integer':
Alexander Makarov committed
230
	case 'int':
231
		$a = (integer)$value;
Alexander Makarov committed
232
		break;
233 234
	case 'boolean':
		$a = (boolean)$value;
Alexander Makarov committed
235
		break;
236 237 238 239 240 241 242 243
	default:
		$a = null;
}
~~~

### Code documentation

- Refer ot [phpDoc](http://phpdoc.org/) for documentation syntax.
244
- Code without documentation is not allowed.
245 246
- All class files must contain a "file-level" docblock at the top of each file
  and a "class-level" docblock immediately above each class.
247
- There is no need to use `@return` if method does return nothing.
248 249 250 251 252 253 254 255 256

#### File

~~~
<?php
/**
 * Component class file.
 *
 * @link http://www.yiiframework.com/
Qiang Xue committed
257
 * @copyright Copyright &copy; 2008 Yii Software LLC
258 259 260 261 262 263 264 265 266 267
 * @license http://www.yiiframework.com/license/
 */
~~~

#### Class

~~~
/**
 * Component is the base class that provides the *property*, *event* and *behavior* features.
 *
Qiang Xue committed
268
 * @include @yii/docs/base-Component.md
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class Component extends \yii\base\Object
~~~


#### Function / method

~~~
/**
 * Returns the list of attached event handlers for an event.
 * You may manipulate the returned [[Vector]] object by adding or removing handlers.
 * For example,
 *
 * ~~~
 * $component->getEventHandlers($eventName)->insertAt(0, $eventHandler);
 * ~~~
 *
 * @param string $name the event name
 * @return Vector list of attached event handlers for the event
 * @throws Exception if the event is not defined
 */
public function getEventHandlers($name)
294
{
295 296 297 298 299
	if (!isset($this->_e[$name])) {
		$this->_e[$name] = new Vector;
	}
	$this->ensureBehaviors();
	return $this->_e[$name];
300
}
301 302
~~~

303 304 305 306 307
#### Comments

- One-line comments should be started with `//` and not `#`.
- One-line comment should be on its own line.

308 309 310 311 312 313 314
Yii application naming conventions
----------------------------------



Other library and framework standards
-------------------------------------
315 316 317 318 319 320 321 322 323

It's good to be consistent with other frameworks and libraries whose components
will be possibly used with Yii2. That's why when there are no objective reasons
to use different style we should use one that's common among most of the popular
libraries and frameworks.

That's not only about PHP but about JavaScript as well. Since we're using jQuery
a lot it's better to be consistent with its style as well.

324 325
Application style consistency is much more important than consistency with other frameworks and libraries.

326 327 328 329 330
- [Symfony 2](http://symfony.com/doc/current/contributing/code/standards.html)
- [Zend Framework 1](http://framework.zend.com/manual/en/coding-standard.coding-style.html)
- [Zend Framework 2](http://framework.zend.com/wiki/display/ZFDEV2/Coding+Standards)
- [Pear](http://pear.php.net/manual/en/standards.php)
- [jQuery](http://docs.jquery.com/JQuery_Core_Style_Guidelines)