Skip to content

Coding Style Guide

Saqib Razzaq edited this page Apr 20, 2019 · 18 revisions

BriskLimbs is no longer a tiny project after the very first release and we expect codebase to grow even larger with time. Hence, it is important that we strictly follow coding styles and best practices to keep it clean and manageable and save other developers some time, pulled out hair and boiled out eyes 😉

Table of Contents

Naming

Files

File names must be either camelCase or lowercase. We strongly suggest to keep file names as short as possible so you don't have to use camelCase but when names are more descriptive, you are welcome to use that.

error.php
upload.php
listUserVideos.php
Classes

All class file names must be in UpperCamelCase. A file must be named exactly the same as class it represents.

A few examples of file names are following

User.php
Videos.php
SettingsManager.php

These classes can then have following content.

class User extends Users {
    // code goes here
}
class Videos {
    // code goes here
}
class SettingsManager extends Settings {
    // code goes here
}
Methods

The method name must use camelCase standard. Each method must explicitly describe the scope.

public function listUsers() {
    // code here
}

private static function keys() {
    // code here
}
Functions

Function names must be camelCase staring with a verb. Examples of verb can be is, get, set, compute, refresh, etc.

getDuration();
setTitle();
isPlayable();

Whitespace, Indentation, and Braces

No tabs. Indents are 2 spaces (configure your editor to convert tabs to 2 spaces). Indent after each new { or block-like construct. The { brace should start on the same line and the } brace ends on own line. Example:

// YES:
for ($i = 0; $i < 10; $i++) {
  for ($j = 0; $j < 10; $j = $j + 2) {
    try {
      if ($i == $j || $i == 0) {
        // ..
      } else if ($i > $j) {
        // ..    
      } else {
        // ..  
      }
    } catch {
      // ..
    }
  }
}

One statement per line, each ending in semi-colon. No trailing whitespace.

// NO:
$foo = 'this'; $bar = 'that';
// YES:
$foo = 'this';
$bar = 'that';

There should be a space before each ( and before each {. There should be a space before and after each operator (+, -, &&, ||, ==, =, etc.). Example:

// NO:
while($i+$j<30 || $i<100) {
  $i=$j + $i*2;
}
// YES:
while ($i + $j < 30 || $i < 100) {
  $i = $j + $i * 2;
}

There should be no space between [ and ] for array access:

// NO:
$array[ $i ]
// YES:
$array[$i]

Blank Lines

Within a PHP file, a single blank line appears:

  • After the initial <?php tag.
  • Blank line before logical groupings of declarations.
  • Blank line before a class or function, but:
  • No blank line between comments and the code them are describing.
  • Within a class/function:
  • No blank lines at the start or end of a class/function body.
  • A blank link can be used in the middle to create groupings of statements.

Example:

<?php

require_once(‘root.inc.php’);
require_once($ROOT . ‘utils/file.php’);
require_once($ROOT . ‘model/account.php’);

ini_set('display_errors', '1');
ini_set('memory_limit', '1024M');

/**
 * A sample class for representing statistics across all accounts.
 */
class AccountStatistics {
  public $accountsList;
  public $totalAccounts;

  public function __construct() {
    $this->accountsList = Account::getAccountsList();
    $this->totalAccounts = count($this->accountsList);
  }
  /**
   * Compute the average balance pending across active accounts.
   */
  public function computeActiveAverageBalance() {
    // First, compute the number of total active accounts.
    $totalActiveAccounts = 0;
    foreach ($this->accountsList as $account) {
      if ($account->isActive()) {
        $totalActiveAccounts++;
      }
    }
    
    // Next, compute the total balance owed in active accounts.
    $totalBalance = 0.0;
    foreach ($this->accountsList as $account) {
      if ($account->isActive()) {
        $totalBalance += $account->getBalance();
      }
    }
    
    return $totalBalance / $totalActiveAccounts;
  }
}

Strings and Primitive Types

Prefer using single quoted strings unless you need variables parsed:

// NO:
“Simple string”

// YES:
‘Simple string’
“String with $variableName”
“String with special character\n”
“String with ‘single quote’”

Strings should be concatenated with a space between the concatenation operator:

// NO:
‘Username: ’.$userName

// YES:
‘Username: ’ . $userName

Long strings should be wrapped with 4 spaces of indentation:

// YES:
$longDummyText = ‘Lorem ipsum dolor sit amet, consectetur adipiscing elit. ’ .
    ‘Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed ’ .
    ‘nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum.’;

Write true, false, and null in lowercase:

// YES:
if ($account == null) {
  return false;
} else {
  return true;
}

Arrays should declared with a space after each “,” or 4 spaces of indentation on following lines as shown below:

// YES:
$domains = array(‘google.com’, ‘yahoo.com’, ‘facebook.com’);
$longDomainsList = array(
    ‘google.com’,
    ‘yahoo.com’,
    ‘facebook.com’);

Comments

Good code should generally be self-explanatory, so comments are generally not required. When used, comments should be used to summarise what classes or functions, or to annotate some aspect that is not obvious in the code:

<?php

/**
 * This class represents a request issued through the HTTP protocol.
 * Usage:
 *   $httpRequest = new HttpRequest();
 *   $content = $httpRequest->getUrl(‘http://ip-check.net/myip’);
 *   print $content;
 */
class HttpRequest {

  /* Get contents from a http:// or https:// URL. */
  public function getUrl($url) {
    try {
      // Note: an exception is thrown if $url cannot be reached.
      return file_get_contents($url);
    } catch (Exception $exception) {
      return false;
    }
  }
}

Frontend

The reason why we use Twig templating engine is to keep backend and frontend completely separate. The logic code should always stay within PHP files while displaying results is part of HTML templates.

// No
{% videos = new Videos() %}
{% results = videos->listFresh(12) %}
{% for video in videos %}
  Title is {{video.title}}
{% endfor %}

// YES
$videos = new Videos();
$limbs->display('videos.html', array('results' => $videos->listFresh(12)));

{% for video in results %}
  Title is {{video.title}}
{% endfor %}

JavaScript and CSS should be placed in separate files as much as possible and try avoiding in-line styles.

// NO
<div style="background-color: red; max-height: 200px;">
	
</div>
// YES
<link rel="stylesheet" type="text/css" href="custom.css">
<div class="custom-styles">
	
</div>

// In custom.css
.custom-styles {
  background-color: red;
  max-height: 200px;
}

Consistency & Judgement

The main purpose of a style guide is to promote consistency. In general, please remember to use your best judgement to ensure that each line of code is written as elegantly as possible!