Coding Standards
When developing N2N we followed the code guidelines below. It is of course up to the developer whether they want to adhere to them.
File Formatting
PHP
In files that contain only PHP code, the closing tag (?>) must be omitted. This prevents unwanted whitespace in the final output.
PHP blocks must always be opened with <?php. <? as well as <?= are not allowed.
CSS
In CSS files the character encoding must be specified on the first line:
@charset "UTF-8";
Control Structures
For control structures the opening brace should be separated from the keyword by a space. After an opening and before a closing curly brace the line should be broken. A space should be inserted between closing and opening braces as well as before and after operators.
// if example
if ($status == $otherStatus || $atusch == true) {
$text = 'Hello';
} elseif ($condition3 && $condition4) {
$sum += 2;
} else {
$sum = $otherSum + $num;
}
// foreach example
foreach ($dsAdvertisements as $key => $rowAdvertisement) {
echo $rowAdvertisement['teig'];
}
// switch example
switch ($sum) {
case 1:
// code here
break;
case 2:
// code here
break;
default:
// code here
break;
}
Longer Statements
Longer statements should be split across multiple lines. Note the double indentation. $conditionX stands for a longer condition.
if ($condition1
&& $condition2
&& $condition3) {
// code here
}
if ($condition1
&& ($condition2
|| $condition3)
&& $condition4
&& $condition5) {
// code here
}
if (($condition1
|| $condition2)
&& $condition3
&& $condition4) {
// code here
}
Variables
For naming variables only the lowercase variant of CamelCase is used (e.g. camelCaseVariable). Constants are an exception, however.
Constants
For constants all letters are uppercase and the individual words are separated by underscores.
define('CFG_APP_NAME', 'advertisementstest');
class Test {
const LIST_SIZE = 20;
}
Strings
A string should generally be delimited with single quotes. If this causes extra effort or line breaks are needed, double quotes may be used instead. A string is concatenated with the '.' operator. A space must be inserted before and after '.'.
// Sample Strings
$sampleString = 'This is a sample string.';
$sampleString2 = 'sampleString contains: ' . $sampleString;
$sampleString3 = \"sampleString2 contains: '\" . $sampleString2 . \"'\";
$sampleString4 = 'This string is followed by a new line' . \"\
\";
To improve readability, longer strings should be split across multiple lines. Depending on the usage, strings do not necessarily have to be split at line breaks. If the string contains a special encoding such as SQL or HTML, the variable name should be prefixed accordingly.
$exampleString = 'n2n is a content management system which, despite ' .
'its extensive range of functions, is very easy to use.';
$htmlExample = '
<div class=\"message\">
<strong>n2n</strong> is a <strong>content management
system</strong> which, despite its extensive range of
functions, is very easy to use.
</div>';
$sqlWhere = ' `id` = 1';
$sql = 'SELECT * FROM `blog_post` WHERE' . $sqlWhere;
SQL
Keywords in SQL statements must always be uppercase. For larger statements, line breaks should be used. For performance and security reasons, prepared statements should be preferred over regular statements for database queries. If PHP variables still need to be inserted directly into the statement, every variable, regardless of its origin, must be "escaped" in the statement.
$type = 'sell';
$userId = 12;
$stmtAdvertisements = $dbh->query('
SELECT advertisement_id, name, type
FROM `advertisement` AS a
INNER JOIN `user` AS u ON a.user_id = u.user_id
WHERE type = ' . $dbh->quote($type) . '
AND user_id = ' . $dbh->quote($userId));
Arrays
$arrTest = array(
'foo' => 'bar',
'spam' => 'ham');
$arrTest['foo'] = 'atusch';
$arrTest[4] = 'atusch';
Classes and Methods
The same rules apply to classes and methods as to control structures. For class names the uppercase variant and for method names the lowercase variant of CamelCase must be used. Further rules can be derived from the following example:
<?php
class Test implements Testable {
private $test;
private $test2;
public function __construct($test, $test2 = null) {
$this->test = $test;
$this->test2 = $test2;
}
public function getTest() {
return $this->test;
}
}
If a call to a method or function becomes too long (e.g. due to many parameters), the call should be split across multiple lines as follows. Note the double indentation:
$numLikes = OrmUtils::createCountCriteria($this->em, Rating::getClass(),
array('suggestion' => $suggestion, 'like' => true))->fetchSingle();
return $this->em->createSimpleCriteria(Suggestion::getClass(), array('online' => true,
'client' => $this->getCurrentClient()),
array('numComments' => 'DESC'), $limit, $num)->fetchArray();
Views
Views begin with a large PHP block in which simple code such as initializing parameters, setting templates, loading CSS, etc. is allowed. After this block only single statements, split into separate PHP code blocks, should occur. Move more complex logic into a model. For control structures in views use the alternative syntax (e.g. if ($x):). With $view->assert() you can ensure that the view was passed valid parameters. Using instanceof in $view->assert() allows your editor to recognize the type of the parameter and offer you autocompletion.
You can find more in the following example:
<?php
use com\example\model\FooModel;
$fooModel = $view->getParam('fooModel');
$view->assert($fooModel instanceof FooModel);
$view->useTemplate('view\template.html');
$html->meta()->addCss('css/foo.css');
?>
<div>
<h2>Bars overview</h2>
<?php if (!$fooModel->hasBars()): ?>
<p>No bars available.</p>
<?php else: ?>
<ul>
<?php foreach ($fooModel->getBars() as $bar): ?>
<li><?php $html->out($bar->getName()) ?></li>
<?php endforeach ?>
</ul>
<?php endif ?>
</div>
Closures
The curly brace should be opened and closed at the same level. Also note the space after function.
$closure = function () {
// code
};
$obj->onEvent(function () {
// code
});
$obj->onOtherEvent($param1, $param2,
function () {
// code
}, $param4);