coding standards for php

Upload: chandrasekar-pitty-balasundaram

Post on 09-Apr-2018

234 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 Coding Standards for PHP

    1/20

    Coding Standards for PHP

    Document Name: Coding Standards for PHP Document Number: ST-PM-001

    Author: Effective Date:

    Document History

    Version No Date Nature of Modification

    1.0 22-Dec-08 Coding standards for PHP

    Page 1 of20 First Page Software Services.

  • 8/8/2019 Coding Standards for PHP

    2/20

    Coding Standards for PHP

    Contents

    1. OVERVIEW

    2. SCOPE

    3. GLOSSARY OF TERMS

    4. STANDARDS

    4.1 Folder Structure4.1.1 Definition4.1.2 Rules To Follow

    4.1.3 Description4.1.4 Example

    4.1.5 Warning

    4.2 Indenting and Line Length

    4.2.1 Definition4.2.2 Rules To Follow

    4.2.3 Description4.2.4 Example

    4.3 Control Structures4.3.1 Definition

    4.3.2 Rules To Follow4.3.3 Example

    4.3.4 Warning

    4.4 Function Calls and Declaration4.4.1 Definition

    4.4.2 Rules To Follow

    4.4.3 Example4.4.4 Warning

    4.5 Comments4.5.1 Definition

    4.5.2 Rules To Follow4.5.3 Description

    4.5.4 Example

    4.5.5 Warning

    4.6 Include Statements4.6.1 Definition

    4.6.2 Rules To Follow4.6.3 Description

    4.6.4 Example4.6.5 Warning

    4.7 Naming Conventions

    Page 2 of20 First Page Software Services.

  • 8/8/2019 Coding Standards for PHP

    3/20

    Coding Standards for PHP

    4.7.1 Definition4.7.2 Rules To Follow

    4.7.3 Description4.7.4 Example

    4.7.5 Warning

    4.8 Database Standards and Conventions4.8.1 Definition

    4.8.2 Rules To Follow4.8.3 Description

    4.8.4 Example4.8.5 Warning

    5. ASSOCIATED PROCESS ELEMENTS

    6. ANNEXURE

    Page 3 of20 First Page Software Services.

  • 8/8/2019 Coding Standards for PHP

    4/20

    Coding Standards for PHP

    1. Overview

    This document basically describes the coding standards and conventions to be followed when

    developing a PHP code.

    2. Scope

    The scope of this document extends to all the projects developed in iProgrammer using PHP asthe web programming language and to all the developers who are going to develop those

    projects. Some of the standards defined this document are generic and may imply to any

    programming language.

    3. Glossary of Terms

    Term/Abbreviation Description

    CL Client

    PM Project ManagerDB Database

    CS Coding Standards

    CC Coding Conventions

    FS Folder Structure

    NC Naming Conventions

    4. Standards

    4.1 Folder Structure

    4.1.1 Definition

    Folder structures refer to different kinds of directories to be maintained whiledeveloping any kind of project where each specific directory contains similar files.

    It is very important to maintain a decent FS to keep the maintenance and usage of

    project files easy.

    4.1.2 Rules to Follow

    The following folders have been identified as part of the web development process:

    includes

    js

    css

    images cron

    functions

    process

    admin

    others

    Page 4 of20 First Page Software Services.

  • 8/8/2019 Coding Standards for PHP

    5/20

    Coding Standards for PHP

    4.1.3 Description

    includes: This folder will include all the configuration files, error handling class,

    database class and any other classes if at all required. There will also be a

    config.inc.php file that will hold all the configuration constants of the site. This fileshould not be uploaded directly but rather a continuous effort should be made to re-

    modify it every time we need to change its contents so that we dont overwrite theprevious data contained in it.

    js: All the java script files will be stored here

    css: All style sheets will be a part of this folder

    images: As the name suggests all the site images should be in this folder including

    flash

    cron: A cron is a program that is scheduled to run periodically. Any cron script should

    get into this folder. The folder should be protected by htaccess so that no one can

    directly run the scripts contained in that folder. This folder is optional.

    functions: All the common PHP functions file, user defined functions file etc should

    come into this folder.

    process: All the business logic of all the form contained pages should be stored in thefiles contained in this folder. Example. Suppose you have a login.php page in themember folder. Then the business logic to validate the user name and password will be

    written in a different file called login.inc.php (assuming that you are submitting theform to the same page) but stored in the folder named process. Refer the example

    part of an actual example.

    admin: All the administrative files will be stored in the admin folder. This folder also in

    turn can have sub-folders i.e. the above 7 folders.

    others: The others folder is a general term for many other folders which can be a partof your project.Example:

    1. registration: All the registration related files and pages should be stored in this

    folder.2. member:If the site contains a member section or any other general public section

    then those files should be kept here. This folder in turn can contain other folders

    like reports, accounts, billing, payment etc depending on the projectrequirement.

    4.1.4 Example

    Example of the usage of the process folder

    So the login.php file in the member folder would like this:

  • 8/8/2019 Coding Standards for PHP

    6/20

    Coding Standards for PHP

    //File to process the business logicinclude(../process/login.inc.php);

    ?>

    Username:

    Password:

    And the actual validation file login.inc.php but in process folder would look like this:

    4.1.5 Warning

    When creating any other folder apart from the standard (1-7) folders, it is required

    that you consult your TL or PM before doing so

    4.2 Indenting and Line Length

    4.2.1 Definition

    Indentation refers to the spacing of the code syntax, which makes it easier to read andunderstand the code.

    Line length refers to the length of the code statement in a single row/line.

    Page 6 of20 First Page Software Services.

  • 8/8/2019 Coding Standards for PHP

    7/20

    Coding Standards for PHP

    4.2.2 Rules to Follow

    Begin writing your code with an indent of a single tab (i.e. n th column of any row

    depending on the editor. In case of Zend, the 5th column. Always use tabs whereverand whenever needed. Do not use white spaces). But the opening php tag should end on thefirst column itself.

    All the control structures, functions, classes etc opening and closing braces should

    start and end on the same column number.

    It is recommended that you break lines at approximately 75-85 characters. There is no

    standard rule for the best way to break a line.

    4.2.3 Description

    Your code should be well intended so that it looks neat and tidy. Anybody who sees

    your code should be able to easily identify the placing of various blocks. Even when

    you review the code after few days it will be easy for you to identify things within the

    code. Some standard editors like Zend have built in facility to indent your code. Youjust need to select your entire code and choose the option to intend your code from

    the menu options

    4.2.4 Example

    Row/Column 1 2 3 4 5 6 7 8 9 10 11 12 13 14..

    12

    34

    5

    67

    89

    10

    1112

    1314

    1516

    17

    181920

    21

    //ends on 1st column

    Page 7 of20 First Page Software Services.

  • 8/8/2019 Coding Standards for PHP

    8/20

    Coding Standards for PHP

    4.3 Control Structures

    4.3.1 Definition

    For controlling the logic of any application we require control structures which includesstatements like if, for, while, switch etc.

    4.3.2 Rules to Follow

    Control statements should have one space between the control keyword and opening

    parenthesis, to distinguish them from function calls.

    Always use curly braces even in situations where they are technically optional. Havingthem increases readability and decreases the likelihood of logical errors being

    introduced when new lines are added.

    For ifstatements if there are multiple conditions, then each condition should be

    enclosed in round braces.

    If there is a single condition inside an if-else statement then use of ternary operators(? :) is always recommended. Ternary operators are generally used when you need to

    collect a specific integer or float value depending on the if-else condition.

    Switch statements are always preferred over "if elseif elseif else" kind of statements.

    Switch statements should always have a default condition.

    4.3.3 Example

  • 8/8/2019 Coding Standards for PHP

    9/20

    Coding Standards for PHP $intPageCount = ($intTotalRecCount % $intPageSize == 0 ? $intTotalRecCount / $intPageSize :

    ceil($intTotalRecCount / $intPageSize));

    ?>

    4.3.4 Warning

    Page 9 of20 First Page Software Services.

  • 8/8/2019 Coding Standards for PHP

    10/20

    Coding Standards for PHP

    While using looping statements like for and while make sure the loops have a

    definitive terminating condition. This is to escape infinite loops.

    4.4 Function Calls and Declarations

    4.4.1 Definition

    Function calls and declarations refer to the way of calling a function definition and theactual declaration of the function.

    4.4.2 Rules To Follow

    Functions should be called with no spaces between the function name, the opening

    parenthesis, and the first parameter, spaces between commas and each parameter,and no space between the last parameter, the closing parenthesis, and the semicolon.

    Here's an example:$intRetVal = fnGetName($intCustID, $strEmail, $strZip);

    All function names should begin with fn followed by the actual function name with

    each breaking work in capital. Arguments with default values should always go at the end of the argument list.

    Always attempt to return a meaningful value from a function, the one that isappropriate.

    4.4.3 Example

  • 8/8/2019 Coding Standards for PHP

    11/20

    Coding Standards for PHP

    }

    ?>

    4.4.4 Warning

    Make sure the function parameters are explicitly verified in the code, arrays arechecked for out-of-bound indexes, variables are initialized before they are used etc.

    4.5 Comments

    4.5.1 Definition

    Comments form one of the most important aspects of the software development

    process. It should be a must to comment your code at regular steps and stages.Consider your comments a story describing the system. Page description, loop

    comments, class comments are one part of the story, method signature comments areanother part of the story, method arguments another part, and method

    implementation yet another part. All these parts should weave together and informsomeone else at another point of time just exactly what you did and why

    4.5.2 Rules To Follow

    Commenting PHP page

    Commenting Functions

    4.5.3 Description

    Commenting PHP page - Each php page should have the following information

    header comment at the very start. The name of the page, its author, creation date,

    last modified by persons name, last modified date and a brief description of what logicthe page contains.

    Commenting Functions - Even functions should be well commented with details like

    who created the function, when was it created, why was it created, what are the

    parameters and their data types and what is the return value of the function. If the

    function is big and complex then it should internally contain inline or block comments.

    Internally your page/function can have two types of comments:

    a) Inline Comments - These are single line comments describing the currentline.

    Syntax: // this is a single line comment

    b) Block Comments - These are used to describe the next 4-5 lines of code (ormay be even more) that logically go together.

    Syntax: /*-----------------------------------------------------------------Description of the code block goes here

    -------------------------------------------------------------------*/

    4.5.4 Example

    Commenting a PHP Page

    Page 11 of20 First Page Software Services.

  • 8/8/2019 Coding Standards for PHP

    12/20

    Coding Standards for PHP

    Commenting Functions

    Inline Comment

    Block Comment

  • 8/8/2019 Coding Standards for PHP

    13/20

    Coding Standards for PHP

    Fetch the user records from the database in descending order.If the user is active then show the subscription details in a green colored

    table. If the user is inactive show the subscription details in a red coloredtable . And so on..

    --------------------------------------------------------------------------------------*/

    //Bad block comment. (Too short) /*---------------------------------------------------------------------------------------

    Fetch the user records and show in different tables.--------------------------------------------------------------------------------------*/

    ?>

    4.5.5 Warning

    When to use Inline and Block comments?Imagine you have to edit someone else code. Do you think it will be easy to understand it

    without good and detailed comments?

    You should use block comment when you want to explain more complex or importantoperation, which is not really obvious for someone else than you. You can use inlinecomment if you want to explain the purpose of these or/and next 1 or 2 lines.

    You are forced to use block comment to describe any logical block of the script

    Don't use block comment every 2 lines of code - TOO OFTEN

    Don't use block comment every 200 lines - NOT ENOUGH

    Of course, you should use comments where it really makes sense.

    Lots of comments like this one:$x = $x + 1; // I incremented $x

    just doesnt add any useful information to the code.

    4.6 Include Statements

    4.6.1 Definition

    This standard explains how to use PHP tags and include statements.

    4.6.2 Rules To Follow

    PHP tags

    Other Include Statements

    4.6.3 Description

    Always use to delimit the PHP code and not the shorthand. This is

    required for PEAR compliance and is also the most portable way to include PHP code

    on differing operating systems and setups.

    Page 13 of20 First Page Software Services.

  • 8/8/2019 Coding Standards for PHP

    14/20

    Coding Standards for PHP

    Anywhere you are unconditionally including a class or library file, use

    require_once().

    Anywhere you are conditionally including a class or library file, use

    include_once().

    Either of these will ensure that the class or library files are included only once.

    They share the same file list, so you don't need to worry about mixing them - a file

    included with require_once() will not be included again by include_once().

    Additionally it is recommended that all of your project includes have the fullyqualified path to the include the file instead of assuming that the user has the current

    directory in the search path. Many PHP implementations don't include the currentdirectory in the path and statements such as include('myfunctions.php') may fail. Use

    the $_CONF['PATH'] variable in the include statement.

    4.6.4 Example

    include($_CONF['PATH'] . "includes/myfunctions.php");

    4.6.5 Warning

    include_once() and require_once() are statements, not functions.

    4.7 Naming Conventions

    4.7.1 Definition

    We should always follow the Hungarian (also called Camel Case) naming

    convention.

    4.7.2 Rules To Follow

    Naming a Class

    Naming Functions and Methods

    Naming Constants

    Predefined Variables

    Variables

    File Naming Conventions

    Form Elements

    4.7.3 Description

    Naming a Class - Classes should be given descriptive names. Avoid using

    abbreviations wherever possible. Class names should always begin with an uppercaseletter prefixed by the word cls.

    Naming Functions and Methods Functions and method names should begin

    with the prefix fn followed by the actual function name with the first letter of each

    breaking word in capital. Functions should in addition have the package name as aprefix, to avoid name collisions between packages. Private class members (meaning

    class members that are intended to be used only from within the same class in whichthey are declared; PHP does not yet support truly-enforceable private namespaces)

    are preceded by pfn.

    Page 14 of20 First Page Software Services.

  • 8/8/2019 Coding Standards for PHP

    15/20

    Coding Standards for PHP

    Naming Constants - Constants should always be all uppercase, with underscores

    to separate words. Prefix constant names with the uppercased name of the

    class/package they are used in. Usually there should be no need to define anyconstants in PHP include files. All constants used in the project must be defined in

    config.inc.php file.

    Predefined Variables - When accessing pre defined variables like form elements,

    session variables, cookies, environment variables, global variables etc do NOT useregular global variables (register_globals=on)butALWAYS use the super globalvariables listed in the below table. Never access any of these mentioned variables

    directly by their name. Assume that register_globals is off and then access thepredefined variables using super global variables.

    Variable Type Access Using Comments

    Server $_SERVER To access any information related to your hosting

    server

    Environment $_ENV To access any environment variables

    HTTP Cookies $_COOKIE To set and access cookies

    HTTP Get $_GET Any name element passed as a query string should

    be accessed using $_GETHTTP Post $_POST Any name element passed using the POST method

    of a form should be accessed using $_POST

    HTTP File Upload $_FILES All the variables created out of the file tag should be

    accessed using $_FILES

    Session $_SESSION All the session variables should be set and accessedusing $_SESSION

    Global variables $GLOBALS To access any global variables

    Variables

    All the variable names must be in bumpy or camel case as mentioned

    above.

    Separate words and parts of variable name with capitalizing first letter ofeach word i.e. simply capitalizing the first alphabet of each breaking word.

    Loop variables should be denoted by $i, $j, $k and so on.

    $sqlQuery1,$sqlQuery2 etc. and $resResult1, $resResult2 etc. are used for

    sql-query string and resource identifier respectively.

    The chart below explains naming variables based on different data types:

    Type Prefix Example

    Integer/Long int $intVariableName

    String str $strVariableName

    Boolean bool $boolVariableName

    Array arr $arrVariableName

    Double/Float dbl $dblVariableNameObject obj $objClassName

    Query sql $sqlQueryName

    Result Set res $resVariableName

    Handle hdl $hdlHandleName

    File Naming Conventions

    Page 15 of20 First Page Software Services.

  • 8/8/2019 Coding Standards for PHP

    16/20

    Coding Standards for PHP

    1. All letters must be in lowercase.

    2. Words are separated by underscores (_).

    3. No matter what use ".php" extension.

    4. Include file extensions: .inc.php.

    5. Class extensions: .class.php.

    6. Keep your file names under 32 chars.7. Name PHP script after what it does and keep important part of the name as

    prefix followed by _ and suffix. You can also use indexes if there are actions

    that require more steps. Be sure names represent a group they belong to.

    8. Good names are: user_add1.php, user_add2.php, user_delete.php,

    report_monthly.php.

    9. Bad names are: adduser.php, userdel.php, mntrep.php.

    10. adduser.php and userdel.php does not tell that both scripts belong to the samelogical group, while point 8) shows the relation between them. It is also

    important to use a prefix for the same group because this way files in thedirectory listing will be placed together. Using indexes you can show the flow of

    the action.

    Form Elements - Forms are an integral part of any web development process. Sogiving meaningful names to each and every form element is important. Please referthe below table on how to name form elements. The naming convention used will be

    Hungarian (camel case).

    Form Elements Prefix Example

    Textbox/Password txt txtFirstName, txtPassword

    Hidden hid hidCustID, hidBillID

    Text Area ta taAddress, taMessage

    Drop down/List Box lst lstState, lstCategory

    File fl FlPath

    Button/Reset/Submit/Image btn btnCancel, btnReset, btnSubmit, btnImage

    Radio Buttons rd rdPayMode, rdSexCheck Boxes chk chkDelete[], chkInActive

    4.7.4 Example

    1. Naming a Class Examples of good class names are:

    clsStudent

    clsError

    clsMail

    2. Naming Functions and Methods fnConnect()

    fnGetData()

    fnBuildSomeWidget()

    fnXML_RPC_serializeData()

    pfnSort()

    pfnInitTree()

    $this->pfnStatus()

    Page 16 of20 First Page Software Services.

  • 8/8/2019 Coding Standards for PHP

    17/20

    Coding Standards for PHP

    3. Naming Constants - PAGE_COUNTER

    PAGE_SIZE

    4.7.5 Warning

    The true, false and null constants are exempted from the all-uppercase rule, andmust always be lowercase.

    For a detailed description and usage of the pre defined variables please refer thePHP manual.

    4.8 Database Standards and Conventions

    4.8.1 Definition

    This section explains all the database standards and conventions to be followed

    while designing a database and using that database in your application.

    4.8.2 Rules To Follow

    General Rules for Database Objects

    Tables

    Table Fields

    Documenting Tables

    Stored Procedures

    Views

    Indexes

    Constraints

    Triggers

    Queries

    4.8.3 Description

    General Rules for Database Objects1. Limit the name to 30 characters.

    2. Use only letters and underscores.3. Do not use spaces in names.

    4. First letter of the name should start with an alphabet

    5. Avoid abbreviations. Try to use full nouns. For example, instead of tblCust, usetblCustomer

    6. Use Hungarian notation. E.g. tblCustomer, spCheckLogin, trWithdrawal

    Tables

    1. Use tbl prefix for table names.

    2. A table is a collection. Its name should be the entity it represents. For examplea. Incorrect: tblCustomers | Correct: tblCustomerb. Incorrect: tblOrders | Correct: tblOrder

    c. Correct: tblOrderDetails

    Table Fields1. Field names should be all UPPER CASE and each word should be separated by

    underscore.

    Page 17 of20 First Page Software Services.

  • 8/8/2019 Coding Standards for PHP

    18/20

    Coding Standards for PHP

    2. Boolean fields should be given names with prefix IS or HAS like"IS_DELETED", "HAS_PERMISSION", or "IS_VALID"

    3. Do not use table name as a prefix to each field.

    Documenting Tables1. Primary Key / Foreign Key

    2. Field Name

    3. Data Type4. Comments Description of the field. Write as much detail as required in this

    column. No need to describe a field that is self evident in the general sense.

    However, some fields might be self-evident to the programmer who makes thisdatabase. But the same field might not be clear to a new programmer who

    joins the team. Such fields should be documented.

    Stored Procedures1. Use sp prefix for Stored Procedures names.

    2. You can group Stored Procedures within a listing by prefix the name withoperations like "spCreate", "spGet", "spUpdate" and "spDelete". You can get a

    list by the parts of an application the stored procedure is used. E.g.spPayroll and spHR.

    Views1. Use vw prefix for View names.

    2. Naming your views should be different depending on the type or purpose of the

    view. For simple views that just join one or more tables with no selectioncriteria, combine the names of the tables joined. For example, joining the

    "Customers" and "StatesAndProvinces" table to create a view of Customers andtheir respective geographical data should be given a name like

    "VwCustomersStatesAndProvinces". For a view that is more like a report, aname like "VwDivisionSalesFor2004" might make more sense.

    Indexes

    1. Use ix prefix for Index names.2. The naming convention for indexes follows this structure:

    ix{TableName}{ColumnsIndexed}{U/N}{C/N}

    where "U/N" is for unique or non-unique and "C/N" is for clustered or non-clustered. "ixProductsIdUC" indicates a unique, clustered index on the Idcolumn of the Products table.

    Constraints1. A prefix gets applied to the constraint name depending on the type

    Primary Key: pk

    Foreign Key: fk

    Check: ckUnique: un

    2. The naming convention syntax for constraints looks like this:

    {pk/fk/ck/un}{constraint type}{table name}_{field name}pkProducts_Id - primary key constraint on the Id field of the Products table.

    Triggers

    1. Use tr prefix for Index names.2. The naming convention for triggers follows this structure:

    tr{Ins/Upd/Del}{table name}where Ins for Insert, Upd for Update and Del for Delete operation.

    trInsEmp is a trigger fired when Insert operation is performed on Emp table.

    Queries1. When writing queries in your code, the query keywords should always be all in

    uppercase. E.g. SELECT NAME FROM tblCustomer WHERE CUST_ID = 1;Notice the keywords SELECT, FROM and WHERE are all in uppercase.

    Page 18 of20 First Page Software Services.

  • 8/8/2019 Coding Standards for PHP

    19/20

    Coding Standards for PHP

    2. In a SELECT query, try to avoid using * to return all the fields or some of thetable fields. Specify each field name separately to be returned.

    4.8.4 Example

    Documenting Tables

    tblRestaurant

    Field Name Data Type Comments

    PK RESTAURANT_ID INT (AUTO)

    FK CUST_ID INT (4)FK to CUST_ID intblCustomer

    RESTAURANT_NAME VARCHAR (200)

    ADDRESS VARCHAR (100)

    CITY VARCHAR (50)

    FK STATE INT (2)FK to STATE_ID intblState

    4.8.5 Warning

    Bloopers:

    The best way to learn progressively is from past mistakes. This section discusses

    some bloopers from our own past documents.

    1. tblUserMaster

    Field Name Data Type Remarks

    USER_ID INT (Identity)

    USER_LOGIN VARCHAR (100) Email id of the user

    USER_PWD VARCHAR (8) Combination of charactersUSER_TYPE VARCHAR (1) S SHEA users

    O - Others

    Remarks:

    Name of the table is incorrect. The use of Master is outdated. The correct tablename is tblUser.

    In the above table, every field name contains the suffix USER. This is a wrong

    practice. Here are field equivalents:a. USER_ID = USER_ID

    b. USER_LOGIN = LOGIN_NAME

    c. USER_PWD = PWDd. USER_TYPE = TYPE

    As far as possible, use full nouns. PWD should be PASSWORD

    The remark for the field USER_PWD is not very descriptive. It should read UsersPassword. It can contain alphabets, numbers, special characters.

    5. Associated Process Elements

    Page 19 of20 First Page Software Services.

  • 8/8/2019 Coding Standards for PHP

    20/20

    Coding Standards for PHP

    Sr.No.

    Document Title Document No. Version Author ReleasedDate

    6. AnnexureNone

    Page 20 of20 First Page Software Services.