Date post: | 04-Jun-2018 |
Category: |
Documents |
Upload: | rs-vinayagam |
View: | 224 times |
Download: | 0 times |
of 37
8/13/2019 Coding Standard PHP
1/37
www.einterviewquestions.com
Coding StandardFor PHPRevision o!"."Created on! #$%ov%#&"'
(ast )odi*ied on! "&%+ul%#&"'
http://www.einterviewquestions.com/http://www.einterviewquestions.com/8/13/2019 Coding Standard PHP
2/37
Table of Contents
" ,uthorisation...............................................................................................................................-
# Revision History..........................................................................................................................
' PHP File Formatting.....................................................................................................................
- Class ames.............................................................................................................................../
)ethod and Function ames.......................................................................................................0
/ Class (i1rary ames...................................................................................................................2
0 )ethod ames............................................................................................................................2
2 Class ,ttri1ute ames.................................................................................................................$
$ )ethod ,rgument ames...........................................................................................................$
"& 3aria1le ames.........................................................................................................................$
"" ,rray 4lement........................................................................................................................."&
"# Single or Dou1le 5uotes..........................................................................................................""
"' Re*erence 3aria1les and Functions Returning Re*erences......................................................""
"- 6lo1al 3aria1les......................................................................................................................""
" De*ine ames 7 6lo1al Constants............................................................................................"#
"/ Static 3aria1les......................................................................................................................."#
"0 Function ames......................................................................................................................"#
"2 4rror Return Chec8 Policy......................................................................................................."#
"$ 9races :; Policy......................................................................................................................"'
#& with ?ey @ords and Functions Policy......................................................................."
## Do ot do Real @or8 in A1Bect Constructors..........................................................................."/
#'
8/13/2019 Coding Standard PHP
3/37
8/13/2019 Coding Standard PHP
4/37
8/13/2019 Coding Standard PHP
5/37
! Revision "istory
# P"P $ile $ormatting
%eneral
www.einterviewquestions.com
Coding Standard
8/13/2019 Coding Standard PHP
6/37
For *iles that contain only PHP codeG the closing tag =IJ> is never permitted.
8/13/2019 Coding Standard PHP
7/37
,ethod and $un(tion Names
sually every method and *unction per*orms an actionG so the name should ma8e clear
what it does! Chec8For4rrors=> instead o* 4rrorChec8=>G DumpDataToFile=> instead o*
DataFile=>. This will also ma8e *unctions and data o1Bects more distinguisha1le.
Su**iEes are sometimes use*ul!
o Max% to mean the maEimum value something can have.
o Cnt% the current count o* a running count varia1le.
o Key% 8ey value.
For eEample! Retry)aE to mean the maEimum num1er o* retriesG RetryCnt to mean the
current retry count.
Pre*iEes are sometimes use*ul!o Is% to as8 a question a1out something. @henever someone sees Isthey will 8now
itKs a question.
o Get% get a value.
o Set% set a value.
For eEample!
8/13/2019 Coding Standard PHP
8/37
se upper case letters as word separatorsG lower case *or the rest o* a word
First character in a name is upper case
o under1ars =KNK>
3ustifi(ation
A* all the di**erent naming strategies many people *ound this one the 1est compromise.
Eample
class ameAneTwo
class ame
4 Class .ibrary Names
ow that name spaces are 1ecoming more widely implementedG name spaces should 1e
used to prevent class name con*licts among li1raries *rom di**erent vendors and groups.
@hen not using name spacesG itKs common to prevent class name clashes 1y pre*iEing
class names with a unique string. Two characters is su**icientG 1ut a longer length is *ine.
Eample
+ohn +ohnsonKs complete data structure li1rary could useJJas a pre*iEG so classes would 1e!
class +B(in8(ist
:
;
5 ,ethod Names
se the same rule as *or class names.
3ustifi(ation
A* all the di**erent naming strategies many people *ound this one the 1est compromise.
Eample
class ameAneTwo
:
*unction Do :;O
*unction Handle4rror=> :;O
;
www.einterviewquestions.com 2
Coding Standard
8/13/2019 Coding Standard PHP
9/37
6 Class Attribute Names
Class mem1er attri1ute names should 1e prepended with the character KmK.
,*ter the KmK use the same rules as *or class names.
KmK always precedes other name modi*iers li8e KrK *or re*erence.
3ustifi(ation
Prepending KmK prevents any con*lict with method names. A*ten your methods and
attri1ute names will 1e similarG especially *or accessors.
Eample
class ameAneTwo
:
*unction 3ar,1c=> :;O
*unction 4rrorum1er=> :;O
var m3ar,1cO
var m4rrorum1erO
var mrameO
;
7 ,ethod Argument Names
The *irst character should 1e lower case.
,ll word 1eginnings a*ter the *irst letter should 1e upper case as with class names.
3ustifi(ation
ou can always tell which varia1les are passed in varia1les.
Eample
class ameAneTwo
:
*unction Startour4ngines=Qsome4ngineG Qanother4ngine> :
this%JmSome4ngine some4ngineO
this%Jm,nother4ngine another4ngineO
;
var mSome4ngineO
var m,nother4ngineO
;
18 9ariable Names
use all lower case letters
www.einterviewquestions.com $
Coding Standard
8/13/2019 Coding Standard PHP
10/37
use KNK as the word separator.
3ustifi(ation
@ith this approach the scope o* the varia1le is clear in the code.
ow all varia1les loo8 di**erent and are identi*ia1le in the code.
Eample
*unction Handle4rror=errorum1er>
:
error new As4rrorO
timeNo*Nerror error%J6etTimeA*4rror=>O
errorNprocessor error%J6et4rrorProcessor=>O
;
11 Array Element
,rray element names *ollow the same rules as a varia1le.
use KNK as the word separator.
donKt use K%K as the word separator
3ustifi(ation
i* K%K is used as a word separator it will generate warnings used with magic quotes.
EamplemyarrK*ooN1arK KHelloKO
print myarr*ooN1ar worldO 77 will output! Hello world
myarrK*oo%1arK KHelloKO
print myarr*oo%1ar worldO 77 warning message
www.einterviewquestions.com "&
Coding Standard
8/13/2019 Coding Standard PHP
11/37
1! Single or ouble :uotes
,ccess an arrayKs elements with single or dou1le quotes.
DonKt use quotes within magic quotes
3ustifi(ation
Some PHP con*igurations will output warnings i* arrays are used without quotes eEcept
when used within magic quotes
Eample
myarrK*ooN1arK KHelloKO
elementNname K*ooN1arKO
print myarr*ooN1ar worldO 77 will output! Hello world
print myarrelementNname worldO 77 will output! Hello world
print myarrKelementNnameK worldO 77 parse error
print myarrelementNname worldO 77 parse error
1# Referen(e 9ariables and $un(tions Returning Referen(es
Re*erences should 1e prepended with KrK.
3ustifi(ation
The di**erence 1etween varia1le types is clari*ied.
:;O
*unction QrStatus=> :;O
;
10 %lobal 9ariables
6lo1al varia1les should 1e prepended with a KgK.
3ustifi(ation
8/13/2019 Coding Standard PHP
12/37
1 efine Names ; %lobal Constants
6lo1al constants should 1e all caps with KNK separators.
3ustifi(ation
O
14 Stati( 9ariables
Static varia1les may 1e prepended with KsK.
3ustifi(ation
:
static msStatus &O
;
15 $un(tion Names
For PHP *unctions use the C 6 convention o* all lower case letters with KNK as the word
delimiter.
3ustifi(ation
:
;
16 Error Return Che(/ Poli(y
Chec8 every system call *or an error returnG unless you 8now you wish to ignore errors.
8/13/2019 Coding Standard PHP
13/37
17 while =condition>
: :
... ...
; ;
Traditional niE policy o* placing the initial 1race on the same line as the 8eyword and
the trailing 1race inline on its own line with the 8eyword!
i* =condition> : while =condition> :
... ...
; ;
3ustifi(ation
,nother religious issue o* great de1ate solved 1y compromise. 4ither *orm is accepta1leG
many peopleG howeverG *ind the *irst *orm more pleasant. @hy is the topic o* many
psychological studies.
There are more reasons than psychological *or pre*erring the *irst style. that supports 1race matchingG the *irst is a much 1etter style. @hyI
(etKs say you have a large 1loc8 o* code and want to 8now where the 1loc8 ends. ou
move to the *irst 1race hit a 8ey and the editor *inds the matching 1race. 4Eample!
i* =veryNlongNcondition QQ secondNveryNlongNcondition>
:
...
;
else i* =...> :
...
;
To move *rom 1loc8 to 1loc8 you Bust need to use cursor down and your 1race matching
8ey. o need to move to the end o* the line to match a 1race then Ber8 1ac8 and *orth.
www.einterviewquestions.com "'
Coding Standard
8/13/2019 Coding Standard PHP
14/37
!8 +ndentation;Tabs;Spa(e Poli(y
:
while =more input>
:
;
;
;
;
www.einterviewquestions.com "-
Coding Standard
8/13/2019 Coding Standard PHP
15/37
!1 Parens ()with =ey >ords and $un(tions Poli(y
Do not put parens neEt to 8eywords. Put a space 1etween.
Do put parens neEt to *unction names.
Do not use parens in return statements when itKs not necessary.
3ustifi(ation
?eywords are not *unctions. 9y putting parens neEt to 8eywords 8eywords and *unction
names are made to loo8 ali8e.
Eample
i* =condition>
:
;
while =condition>
:
;
strcmp=sG s">O
return "O
www.einterviewquestions.com "
Coding Standard
8/13/2019 Coding Standard PHP
16/37
!! o Not do Real >or/ in ?b@e(t Constru(tors
Do not do any real wor8 in an o1BectKs constructor. method *or an o1Bect which completes construction. Apen=> should 1e
called a*ter o1Bect instantiation.
3ustifi(ation
Constructors canKt return an error.
Eample
class Device
:
*unction Device=> : 7U initialiMe and other stu** U7 ; *unction Apen=> : return F, eEit=">O
,a/e $un(tions Reentrant
Functions should not 8eep static varia1les that prevent a *unction *rom 1eing reentrant.
www.einterviewquestions.com "/
Coding Standard
8/13/2019 Coding Standard PHP
17/37
!# +f Then Else $ormatting
.ayout
77 Comment :
;
else i* =condition> 77 Comment
:
;
else 77 Comment
:
;
...
Ane reason is that i* you leave out one o* the signsG the parser will *ind the error *or you. ,
second reason is that it puts the value you are loo8ing *or right up *ront where you can *ind
it instead o* 1uried at the end o* your eEpression.
8/13/2019 Coding Standard PHP
18/37
!0 switch$ormatting
Falling through a case statement into the neEt case statement shall 1e permitted as long
as a comment is included.
The defaultcase should always 1e present and trigger an error i* it should not 1e
reachedG yet is reached.
:
case "!
...
77 F,(( THRA6H
case #!
:
v getNwee8Nnum1er=>O
...
;
1rea8O
de*ault! ;
2se of continuebreakand B
www.einterviewquestions.com "2
Coding Standard
8/13/2019 Coding Standard PHP
19/37
! Continue and 1rea8O
;
ote! , lot o* code is necessary in order that the pro1lem cannot 1e caught easily 1y
the programmer.
From the a1ove eEampleG a *urther rule may 1e given! )iEing continue with 1rea8 in the
same loop is a sure way to disaster.
B
The trou1le is people usually try and stu** too much code in 1etween the ?and :. Here are a
couple o* clarity rules to *ollow!
Put the condition in parens so as to set it o** *rom other code
8/13/2019 Coding Standard PHP
20/37
Eample
=condition> I *unct"=> ! *unc#=>O
or
=condition>
I long statement ! another long statementO
www.einterviewquestions.com #&
Coding Standard
8/13/2019 Coding Standard PHP
21/37
!4 Alignment of e(laration .
!5 o(ument Null Statements,lways document a null 1ody *or a *or or while statement so that it is clear that the null 1ody
is intentional and not missing code.
while =destVV srcVV>
O 77 3A
8/13/2019 Coding Standard PHP
22/37
!6 o Not efault +f Test to Non-Dero
Do not de*ault the test *or non%MeroG i.e.
i* =F,>
is 1etter than
i* =*=>>
even though F,O instead test *or inequality
with & =F,(S4G AG etc.>. )ost *unctions are guaranteed to return & i* *alseG 1ut only non%Mero
i* true. ThusG
i* =TR4 *unc=>> : ...
must 1e written
i* =F,(S4 L *unc=>> : ...
www.einterviewquestions.com ##
Coding Standard
8/13/2019 Coding Standard PHP
23/37
#8 2sually Avoid Embedded Assignments
There is a time and a place *or em1edded assignment statements. >>
:
process the character
;
The VV and %% operators count as assignment statements. SoG *or many purposesG do
*unctions with side e**ects. sing em1edded assignment statements to improve run%time
per*ormance is also possi1le. HoweverG one should consider the tradeo** 1etween increased
speed and decreased maintaina1ility that results when em1edded assignments are used in
arti*icial places. For eEampleG
a 1 V cO
d a V rO
should not 1e replaced 1y
d =a 1 V c> V rO
even though the latter may save one cycle. or/ of ?thers
Reuse across proBects is almost impossi1le without a common *ramewor8 in place. A1Bects
con*orm to the services availa1le to them. Di**erent proBects have di**erent service
environments ma8ing o1Bect reuse di**icult.
Developing a common *ramewor8 ta8es a lot o* up *ront design e**ort. @hen this e**ort is not
madeG *or whatever reasonsG there are several techniques one can use to encourage reuse!
onKt be Afraid of Small .ibraries
Ane common enemy o* reuse is people not ma8ing li1raries out o* their code. , reusa1le
class may 1e hiding in a program directory and will never have the thrill o* 1eing shared
1ecause the programmer wonKt *actor the class or classes into a li1rary.
Ane reason *or this is 1ecause people donKt li8e ma8ing small li1raries. ThereKs something
a1out small li1raries that doesnKt *eel right. 6et over it. The computer doesnKt care how
many li1raries you have.
www.einterviewquestions.com #'
Coding Standard
8/13/2019 Coding Standard PHP
24/37
8/13/2019 Coding Standard PHP
25/37
Comment .ayout
4ach part o* the proBect has a speci*ic comment layout.
www.einterviewquestions.com #
Coding Standard
8/13/2019 Coding Standard PHP
26/37
,a/e %ot(has Epli(it
4Eplicitly comment varia1les changed out o* the normal control *low or other code li8ely to
1rea8 during maintenance. 4m1edded 8eywords are used to point out issues and potential
pro1lems. Consider a ro1ot will parse your comments loo8ing *or 8eywordsG stripping them
outG and ma8ing a report so people can ma8e a special e**ort where needed.
%ot(ha =eywords
T?? topi(
)eans thereKs more to do hereG donKt *orget.
8/13/2019 Coding Standard PHP
27/37
77 !?(D64! tmh $/&2"&! possi1le unsa*e type cast
77 @e need a cast here to recover the derived type.
8/13/2019 Coding Standard PHP
28/37
## ire(tory o(umentation
4very directory should have a R4,D)4 *ile that covers!
the purpose o* the directory and what it contains
a one line comment on each *ile. , comment can usually 1e eEtracted *rom the ,)4
attri1ute o* the *ile header.
cover 1uild and install directions
direct people to related resources!
o directories o* source
o online documentation
o paper documentation
o design documentation
anything else that might help someone
Consider a new person coming in / months a*ter every original person on a proBect has gone.
That lone scared eEplorer should 1e a1le to piece together a picture o* the whole proBect 1y
traversing a source directory tree and reading R4,D)4 *ilesG )a8e*ilesG and source *ile
headers.
?pen;Closed Prin(iple
The Apen7Closed principle states a class must 1e open and closed where!
open means a class has the a1ility to 1e eEtended.
closed means a class is closed *or modi*ications other than eEtension. The idea is once a
class has 1een approved *or use having gone through code reviewsG unit testsG and other
quali*ying proceduresG you donKt want to change the class very muchG Bust eEtend it.
The Apen7Closed principle is a pitch *or sta1ility. , system is eEtended 1y adding new code
not 1y changing already wor8ing code. Programmers o*ten donKt *eel com*orta1le changing
old code 1ecause it wor8sL This principle Bust gives you an academic sounding Busti*ication *or
your *ears !%>
8/13/2019 Coding Standard PHP
29/37
#0 Server (onfiguration
This section contains some guidelines *or PHP7,pache con*iguration.
"TTPO9ARS
HTTPNUN3,RS are either ena1led or disa1led. @hen ena1led all varia1les must 1e accessed
through HTTPNUN3,RS8ey. @hen disa1led all varia1les can 1e accessed 1y the 8ey name.
use HTTPNUN3,RS when accessing varia1les.
use ena1led HTTPNUN3,RS in PHP con*iguration.
3ustifi(ation
HTTPNUN3,RS is availa1le in any con*iguration.
HTTPNUN3,RS will not con*lict with eEsisting varia1les.
sers canKt change varia1les 1y passing values.
# P"P $ile Etensions
There is lots o* di**erent eEtension variants on PHP *iles =.htmlG .phpG .php'G .php-G .phtmlG
.incG .class...>.
,lways use the eEtension .php.
,lways use the eEtension .php *or your class and *unction li1raries.
3ustifi(ation
The use o* .php ma8es it possi1le to ena1le caching on other *iles than .php.
The use o* .inc or .class can 1e a security pro1lem. An most servers these eEtensions
arenKt set to 1e run 1y a parser. .
Do not rely on automatic 1eauti*iers. The main person who 1ene*its *rom good program
style is the programmer him7hersel*G and especially in the early design o* handwritten
algorithms or pseudo%code. ,utomatic 1eauti*iers can only 1e applied to completeG
syntactically correct programs and hence are not availa1le when the need *or attention to
white space and indentation is greatest. Programmers can do a 1etter Bo1 o* ma8ing clear
the complete visual layout o* a *unction or *ileG with the normal attention to detail o* a
care*ul programmer =in other wordsG some o* the visual layout is dictated 1y intent rather
than syntaE and 1eauti*iers cannot read minds>. Sloppy programmers should learn to 1e
care*ul programmers instead o* relying on a 1eauti*ier to ma8e their code reada1le.
www.einterviewquestions.com #$
Coding Standard
8/13/2019 Coding Standard PHP
30/37
FinallyG since 1eauti*iers are non%trivial programs that must parse the sourceG a
sophisticated 1eauti*ier is not worth the 1ene*its gained 1y such a program. 9eauti*iers
are 1est *or gross *ormatting o* machine%generated code.
,ccidental omission o* the second ZZKK o* the logical compare is a pro1lem. The *ollowing
is con*using and prone to error. i* =a1ool 11ool> : ... ;
Does the programmer really mean assignment hereI A*ten yesG 1ut usually no. The
solution is to Bust not do itG an inverse i8e philosophy. : ... ;
2se if )8* to Comment ?ut Code 1loc8!
*unction eEample=>
:
great loo8ing code
i* =&> :
lots o* code
;
more code
;
ou canKt use ;OO;style comments 1ecause comments canKt contain comments and surely alarge 1loc8 o* your code will contain a commentG wonKt itI
www.einterviewquestions.com '&
Coding Standard
8/13/2019 Coding Standard PHP
31/37
#4 ifferent A((essor Styles
+mplementing A((essors
There are two maBor idioms *or creating accessors.
%et;Set
class [
:
*unction 6et,ge=> : return this%Jm,geO ;
*unction Set,ge=age> : this%Jm,ge ageO ;
var m,geO
;O
6et7Set is ugly. 6et and Set are strewn throughout the code cluttering it up.
9ut one 1ene*it is when used with messages the set method can transparently trans*orm
*rom native machine representations to networ8 1yte order.
Attributes as ?b@e(ts
class [
:
*unction ,ge=> : return this%Jm,geO ;
*unction ame=> : return this%JmameO ;
var m,geO
var mameO
;
E new [O
77 4Eample "
age E%J,ge=>O
rNage QE%J,ge=>O 77 Re*erence
77 4Eample #
name E%Jame=>O
rNname QE%Jame=>O 77 Re*erence
,ttri1utes as A1Bects is clean *rom a name perspective. @hen possi1le use this approach to
attri1ute access.
www.einterviewquestions.com '"
Coding Standard
8/13/2019 Coding Standard PHP
32/37
#5 .ayering
(ayering is the primary technique *or reducing compleEity in a system. , system should 1e
divided into layers. (ayers should communicate 1etween adBacent layers using well de*ined
inter*aces. @hen a layer uses a non%adBacent layer then a layering violation has occurred.
, layering violation simply means we have dependency 1etween layers that is not controlled
1y a well de*ined inter*ace. @hen one o* the layers changes code could 1rea8. @e donKt
want code to 1rea8 so we want layers to wor8 only with other adBacent layers.
Sometimes we need to Bump layers *or per*ormance reasons. This is *ineG 1ut we should
8now we are doing it and document appropriately.
#6 Code Reviews
8/13/2019 Coding Standard PHP
33/37
#7 Create a Sour(e Code Control System Early and Not ?ften
, common 1uild system and source code control system should 1e put in place as early as
possi1le in a proBectKs li*ecycleG pre*era1ly 1e*ore anyone starts coding. Source code control
is the structural glue 1inding a proBect together.
8/13/2019 Coding Standard PHP
34/37
Create a
8/13/2019 Coding Standard PHP
35/37
*ormats will cause con*licts with persistent stores or remote message sending then say so.
8/13/2019 Coding Standard PHP
36/37
01 No ,agi( Numbers
, magic num1er is a 1are%na8ed num1er used in source code.
8/13/2019 Coding Standard PHP
37/37
0! Thin vs' $at Class +nterfa(es
How many methods should an o1Bect haveI The right answer o* course is Bust the right
amountG weKll call this the 6oldiloc8s level. 9ut what is the 6oldiloc8s levelI
The two eEtremes are thinclasses versus thi(/classes. Thin classes are minimalist classes.
Thin classes have as *ew methods as possi1le. The eEpectation is users will derive their own
class *rom the thin class adding any needed methods.
@hile thin classes may seem clean they really arenKt. ou canKt do much with a thin class.