III.A. PHP Code Demarcation
PHP code must always be delimited by the full-form, standard PHP tags. Short tags are never allowed.
Justification
is always available in any system and setup
Example
<?php= 'Hello world'; ?> //Will print "Hello world"
III.B. Braces {} Policy
Of the three major brace placement strategies, two are acceptable, with the one listed below as being preferable and the one we will use.
Traditional Unix policy (and Zend Studio method) of placing the initial brace on the same line as the keyword and the trailing brace inline on its own line with the keyword:
if(condition) {
...
}
while(condition) {
...
}
Justification
Since we will be using Zend Studio as our rpeferred editor, the above method is automatic.
III.C. Indentation / Tabs / Space Policy
- Indent using 4 spaces for each level.
- Do not use tabs, use spaces. Most editors can substitute spaces for tabs.
- Indent as much as needed, but no more. There are no arbitrary rules as to the maximum indenting level. If the indenting level is more than 4 or 5 levels you may think about factoring out code.
Justification
- When people use different tab settings the code is impossible to read or print, which is why spaces are preferable to tabs.
- Most PHP applications use 4 spaces.
- Most editors use 4 spaces by default.
- As much as people would like to limit the maximum indentation levels it never seems to work in general. We'll trust that programmers will choose wisely how deep to nest code.
Example
function func() {
if(something bad) {
if(another thing bad) {
while(more input) {
...
}
}
}
}
III.D. Parens () With Key Words and Functions Policy
- Do not put parens next to keywords. Put a space between.
- Do put parens next to function names
- Do not use parens in return statements when it's not necessary.
Justification
Keywords are not functions. By putting parens next to keywords, keywords and function names are made to look alike.
Example
if(condition) {
}
while(condition) {
}
strcmp($foo, $bar);
return 1;
function someFunction() {
}
III.E. If, Then, Else Formatting
Layout
While there are many different bracing styles, the approach we will use is:
if(condition) {
}
elseif(condition) {
}
else {
}
Condition Format
Always put the constant on the left-hand side of an equality/inequality comparison. For example:
if(6 == $errorNum) ...
One reason is that if you leave out one of the = signs, the aprse will find the error for you. A second reason is that it puts the value you are looking for right up front where you can find it instead of buried at the end of your expression. It takes a little time to get used to this format, but then it really gets useful.
III.F. Switch Formatting
Control statements written with the "switch" construct must have a single space before the opening parens of the conditional statement, and also a single space after the clsoing parens.
All content within the "switch" statement must be indented four spaces. Content under each "case" statement must be indented an additional four space.
Example
switch($numPeople) {
case 1:
//break intentially omitted
//fall-through
case 2:
break;
default:
break;
}
The construct default may never be omitted from a switch statement.
NOTE: It is sometimes useful to write a case statement which falls through to the next case by not including a break or return in that case. To distinguish these cases from bugs, any case statement where break or return are omitted must contain the comment "//break intentionally omitted".
III.G. Use of continue, break, and ?:
Continue and Break
Continue and break are relly disguised gotos so they are covered here.
Continue and break, like goto, should be used sparingly as they are magic in code. With a simple spell the reader is beamed to god knows where for some usually undocumented reason.
The two main problems with continue are:
- It may bypass the test condition
- It may bypass the increment/decrement expression
Consider the following example where both problems occur
while(TRUE) {
...
//A lot of code
...
if(*/ some condition */) {
continue;
}
...
//A lot of code
...
if($i++ > STOP_VALUE) {
break;
}
Note: "A lot of code" is necessary in order that the problem cannot be easily caught by the programmer
From the above example, a further rule may be given: Mixing continue with break in the same loop is a sure way to disaster.
?:
The trouble is people usually try and stuff too much code in between the ? and :. Here are a couple of clarity rules to follow:
- Put the condition in parens so as to set it off from other code.
- If possible, the actions for the test should be simple functions.
- Put the action for the then and else statement on a separate line unless it can be clearly put on one line.
Example
(condition)
? long statement
: another long statement;
III.H. Alignment of Declaration Blocks
Blocks of declarations should be aligned
Justification
- Clarity.
- Similar blocks of initialization variables should be tabulated.
Example
public $date;
public $name;
$date = 0;
$rDate = NULL;
$name = 0;
III.I. Strings
String Literals
When a string is literal (contains no variable substitutions), the apostrophe or "single quote" must always be used to demarcate the string:
$a = 'Example String';
String Literals Containting Apostrophes
When a literal itself contains apostraphes, it is permitted to demarcate the string with quotation marks, or "double quotes". This especially encouraged for SQL statements:
$queryString = "
SELECT
`id`,
`name`
FROM
`people`
WHERE
`name`='Fred'
OR
`name`='Susan'
";
Variable Substitution and Concatenation
Variable substitution is not permitted, and concatenation should always be used instead. Strings must be concatenated using the "." operator. A space must always be added before and after the "." to improve readablity:
$company = 'Live' . 'Office';
When concatenating strings with the "." operator, it is permitted to break statements into multiple lines to improve readablity. In these cases, each successive line should be paddid with whitespace such that the "." operator is aligned under the "=" operator:
$concatString = "The dog ran "
. "through the "
. "woods very fast";
III.J. Classes
Class Declaration
Classes must be named by the following naming conventions:
- The brace is always written on the same line as the class declaration.
- Every class must have docmentation block that conforms to the PHPDocumentor standard.
- Any code with in a class must be indented four spaces.
- Only one class is permitted per PHP file.
- Placing additional code in a class file is permitted but discouraged. In these files, two blank lines must separate the class any additional PHP code in the file.
/**
* Documentation Block Here
*/
class SampleClass {
//entire content of class
//must be indented four spaces
}
Class member functions
Call class must be use by the following naming conventions:
- Use parent:: when calling a parent function
- Use self:: when calling a function in the current class
/**
* Documentation Block Here
*/
class SampleClass extends MainClass{
[...]
public function __construct() {
[...]
self::validate();
}
public function validate() {
return parent::validate();
}
}
Class Member Variables
Member variables must be named by the following conventions:
- Any variables declared in a class must be listed at the top of the class, prior to declaring any functions
- You may not initialize any variables at declaration, initialization is to be done in the constructor
- Class variables follow the same naming convention as all variables
- The var construct is not permitted. Member variables always declare their visibility by usining one of the private,protected, or public constructs.
Example
/**
* nameonetwo.class.php
*
* NameOneTwo class file.
* @author [Author Name]
* @version 1.0
* @copyright Copyright 2010, MyName
* @package VCC5
*/
class NameOneTwo {
public $var1; //comment your declarations
public $var2; //comment your declarations
public $var3; //comment your declarations
/**
* class constructor
*/
function __construct() {
$this->var1 = NULL;
$this->var2 = NULL;
$this->var3 = NULL;
}
//other functions and code
}
III.K. SQL Queries
The following formatting convention should be used for all SQL statements to allow for readability and easy copying and pasting into utilities such as phpMyAdmin or MySQL-Front for error-checking.
Query should be write with double-quote and always use the tablename before selecting a field or using in the where clause.
SELECT Without LEFT JOIN
$queryString = "
SELECT
`table`.`field1`
FROM
`table`
WHERE
`table`.`field2` = ''
";
SELECT With LEFT JOIN
$queryString = "
SELECT
`table1`.`name`,
`table2`.`name`
FROM
`table1`
LEFT JOIN
`table2`
ON
`table1`.`PK_ID` = `table2`.`FK_ID`
WHERE
`table1`.`key` = " . (int)$value;
INSERT
$queryString = "
INSERT INTO
`table`
SET
`field` = '" . (string)$value . "',
`field2` = '" . (string)$anotherValue . "'
";
UPDATE
$queryString = "
UPDATE
`table`
SET
`field` = '" . (string)$value . "',
`field2` = '" . (string)$anotherValue . "'
WHERE
`key` = " . (int)$keyValue;
III.L. SQL Stored Procedures & Views
All stored procedure names must begin with "proc_" and all views start with "view_".
Stored procedures call will use the following convention. After the "proc_" prefix, the procedure will be named [action][table name].
The procedure name uses the same conventions as function names (camel caps). The following are acceptable actions:
- select — ** We don't use procedure for SELECT
- insert — insert procedures. These include validations to check if primary key exists
- update — update procudures. These include validations to check if primary key exists
- delete — delete procedures. These include validations to check if primary key exists
Example:
proc_insertClient(100);
If a procedure performs multiple functions ie: 1 or more insert, select, and update or delete.
A generic name that describes the procedure should be used.
Example:
proc_authentication();
In the case of procedures that are used by modules they should be prefixed with "module" after "proc_"
Example:
proc_moduleInstallClient();
Stored procedures will use the following convention.
For main procedure we will use the SQLEXCEPTION HANDLER to Rollback the transaction.
All type for parameters or declared variable can be the MySQL type. The parameters can be optional.
DELIMITER $$;
DROP PROCEDURE IF EXISTS `virtual_call_center`.`proc_name`$$
CREATE PROCEDURE `virtual_call_center`.`proc_name`(
IN `IN_varName` VARCHAR(50)
)
BEGIN
DECLARE `v_variableOne` INT(11);
DECLARE EXIT handler FOR SQLEXCEPTION BEGIN SELECT 0 as result; ROLLBACK; END;
#SQL STATEMENT
#Procedure condition
SELECT 1 as result;
COMMIT;
END$$
DELIMITER ;$$
III.M. Print Margin Column
Never write text after the Print Margin Column (Column 80).
When programming, you don't want to scroll horizontal to see what is your code and get lost.
Example:
if(isset($id) && $id == 0 && is_array($userTable) && in_array($id, $userTable) && $_SESSION['userId'] !== NULL) {
[...]
}
Make your line easy to read.
if(isset($id)
&& $id === 0
&& is_array($userTable)
&& in_array($id, $userTable)
&& $_SESSION['userId'] !== NULL) {
//[...]
}
III.N. IF/ELSE block in function.
For several validation in a function,
make sure that all those validation are seperate.
With that, that make the code easy to read.
Example:
if(isset($id)) {
if($id === 0) {
if(is_array($userTable)) {
if(in_array($id, $userTable)) {
if($_SESSION['userId'] !== NULL) {
return true;
}
}
}
}
}
return false;
Those condition could be hard to read if you have many overlapping if.
if(!isset($id)) {
//[...]
return false;
}
if($id !== 0) {
//[...]
return false;
}
if(!is_array($userTable)) {
//[...]
return false;
}
if(!in_array($id, $userTable)) {
//[...]
return false;
}
if($_SESSION['userId'] === NULL) {
//[...]
return false;
}
//[...]
return false;
III.O. Log File.
Standard for log file is:
[date] [user ip session_code] [action] message. [LF]
date: Date formated D M d H:i:s Y
user: Username
ip: IP
session: Session id
action: Action
message: Message related
Example:
[Fri Oct 06 09:01:00 2007] [user 127.0.0.1 1234567890] [action] This is the action.
III.P. Patch File.
Standard for patch file is:
# Date in format :D M d H:i:s Y
# Owner Name
# Delete from the table all the rows and optimize this table.
--- Start Statement ---
SQL Statement
--- End Statement ---
LF
Example:
# Fri Oct 06 09:00:00 2007
# John Doe
# Delete from the table all the rows and optimize this table.
--- Start Statement ---
DELETE from `table`;
OPTIMIZE TABLE `table`;
--- End Statement ---