CakePHP Developers will use the PSR-2 Coding Standards guide in addition to the following rules as coding standards. You can use the CakePHP Code Sniffer to check that your coding follows the required standards.
IDE Setup
Please make sure your IDE is set up to “trim right” on whitespaces. There should be no trailing spaces per line.
Indentation
Four spaces should be used for indentation.
Example:
// base level
// level 1
// level 2
// level 1
// base level
If you are using the multiline function call then follow the following guidelines.
- Opening the parenthesis of a multi-line function call must be the last content on the line.
- Only one argument is allowed per line in a multi-line function call.
- Closing parenthesis of a multi-line function call must be on a line by itself Instead of using the following formatting:
$matches = array_intersect_key($this->_listeners,
array_flip(preg_grep($matchPattern,
array_keys($this->_listeners), 0)));
Use this instead:
$matches = array_intersect_key(
$this->_listeners,
array_flip(
preg_grep($matchPattern, array_keys($this->_listeners), 0)
)
);
Line Length
It is recommended to keep lines at approximately 100 characters long for better coding readability. Lines must not be longer than 120 characters.
Control Structures
- In the control structures, there should be 1 (one) space before the first parenthesis and 1 (one) space between the last parenthesis and the opening bracket.
- Always use curly brackets in control structures, even if they are not needed. They increase the readability of the code, and they give you fewer logical errors.
- Opening curly brackets should be placed on the same line as the control structure. Closing curly brackets should be placed on new lines, and they should have the same indentation level as the control structure. The statement included in curly brackets should begin on a new line, and coding contained within it should gain a new level of indentation.
- Inline assignments should not be used inside of the control structures. Below is an example of ‘if’:
if ((expr_1) || (expr_2)) {
// action_1;
} elseif (!(expr_3) && (expr_4)) {
// action_2;
} else {
// default_action;
}- if (expr) statement; ( wrong = no brackets, badly placed )
- if (expr) ( wrong = no brackets )
statement; - if (expr) { ( good )
statement;
} - if ($variable = Class::function()) { ( wrong = inline assignment )
statement;
} - $variable = Class::function(); ( good )
if ($variable) {
statement;
}
Ternary operator
Ternary operators are permissible when the entire ternary operation fits on one line. Longer ternaries should be split into if-else statements. Ternary operators should not ever be nested. Optionally parentheses can be used around the condition check of the ternary for clarity:
// Good, simple and readable
$variable = isset($options['variable']) ? $options['variable'] : true;
// Nested ternaries are bad
$variable = isset($options['variable']) ? isset($options['othervar']) ? true : false : false;
Template Files
In template files (.ctp files) developers should use keyword control structures. Keyword control structures are easier to read in complex template files. Control structures can either be contained in a larger PHP block, or in separate PHP tags:
<?php
if ($isAdmin):
echo '<p>You are the admin user.</p>';
endif;
?>
<p>The following is also acceptable:</p>
<?php if ($isAdmin): ?>
<p>You are the admin user.</p>
<?php endif; ?>
Comparison
Always try to be as Strict as possible:
For testing if a variable is null, it is recommended to use a strict check:
if ($value === null) {
// ...
}
The value to check against should be placed on the right side:
// not recommended
if (null === $this->foo()) {
// ...
}
// recommended
if ($this->foo() === null) {
// ...
}
Function Calls
Functions should be called without space between the function’s name and starting parenthesis. There should be one space between every parameter of a function call:
$var = foo($bar, $bar2, $bar3);
Method Definitions
public function someFunction($arg1, $arg2 = '')
{
if (expr) {
statement;
}
return $var;
}
Parameters with a default value should be placed last in the function definition. Try to make your functions return something, at least true or false, so it can be determined whether the function call was successful:
Bail Early
Try to avoid unnecessary nesting by bailing early:
public function run(array $data)
{
...
if (!$success) {
return false;
}
...
}
Type Hinting
Arguments that expect objects, arrays, or callbacks (callable) can be type hinted. We only type-hint public methods, though, as type hinting is not cost-free:
public function foo(Table $table, array $array, callable $callback, $boolean){}
Here $table must be an instance of \Cake\ORM\Table, $array must be an array and $callback must be of type callable (a valid callback).
Method Chaining
Method chaining should have multiple methods spread across separate lines, and indented with four spaces:
$email->from('foo@example.com')
->to('bar@example.com')
->subject('A great message')
->send();
Including Files
include, require, include_once, and require_once do not have parentheses:
// wrong = parentheses
require_once('ClassFileName.php');
require_once ($class);
// good = no parentheses
require_once 'ClassFileName.php';
require_once $class;
When including files with classes or libraries, use only and always the require_once function.
PHP Tags
Always use long tags (<?php ?>) instead of short tags (<? ?>). The short echo should be used in template files (.ctp) where appropriate.
Short Echo
The short echo should be used in template files in place of // wrong = semicolon, no spaces
<td><?=$name;?></td>
// good = spaces, no semicolon
<td><?= $name ?></td>
Naming Conventions
Functions:
Write all functions in the camelBack case.
function longFunctionName()
{
}
Classes:
Class names should be written in CamelCase, for example:
class ExampleClass
{
}
Variables:
Variable names should be as descriptive as possible, but also as short as possible. All variables should start with a lowercase letter and should be written in camelBack in case of multiple words. Variables referencing objects should in some way associate to the class a variable is an object of. Example:
$user = 'John';
$users = ['John', 'Hans', 'Arne'];
$dispatcher = new Dispatcher();
Member Visibility
Use PHP’s public, protected, and private keywords for methods and variables.
Files
File names which do not contain classes should be lowercase and underscore, for example:
long_file_name.php
Type Casting
Please use (int)$var instead of intval($var) and (float)$var instead of floatval($var) when applicable in Type Casting.
Constants
Constants should be defined in capital letters:
define('CONSTANT', 1);
Careful when using the empty() / isset()
While empty() is easy to use the function, it can mask errors and cause unintended effects when ‘0’ and 0 are given. When variables or properties are already defined, the usage of empty() is not recommended. When working with variables, it is better to rely on type-coercion to boolean instead of empty():
function manipulate($var)
{
// Not recommended, $var is already defined in the scope
if (empty($var)) {
// ...
}
// Use boolean type coercion
if (!$var) {
// ...
}
if ($var) {
// ...
}
}
When dealing with defined properties you should favor null checks over empty()/isset() checks:
class Thing
{
private $property; // Defined
public function readProperty()
{
// Not recommended as the property is defined in the class
if (!isset($this->property)) {
// ...
}
// Recommended
if ($this->property === null) {
}
}
}
When working with arrays, it is better to merge in defaults instead of using empty() checks. By merging in defaults, you can ensure that the required keys are defined:
function doWork(array $array)
{
// Merge defaults to remove the need for empty checks.
$array += [
'key' => null,
];
// Not recommended, the key is already set
if (isset($array['key'])) {
// ...
}
// Recommended
if ($array['key'] !== null) {
// ...
}
}
jQuery presents a tree-like structure of all the elements on a webpage simplifying the syntax and further manipulating such elements. The jQuery Certification Exam by StudySection will secure your fundamental knowledge and a basic understanding of jQuery as an asset to improve your skills.