10 Pillars of Modern PHP Development - Fortrabbit Blog
10 Pillars of Modern PHP Development - Fortrabbit Blog
development
PHPdevelopmentthenandnow
FormostofusPHPdeveloperswritingapplicationsnowcomparedtotenorsoyearsagois
quiteadifferentendeavor.Backthen,manyofuswereratherwebdesignersresponsible
notonlyforbackenddevelopment,butdatabaseengineering,systemadministration,
frontendprogrammingandmaybeconceivinganddesigningtheveryUIaswell.
Thishaschangedinrecentyears.Classicalwebsitesarebecomingmoreandmorethe
domainofspecializedSaaSwhywriteanotherblogengine,cooperatehomepageCMSor
smalltimeecommercesystemiftherearealreadysomanyavailablefor(nearly)free?Orto
putittheotherwayaround:everythingwhichcanbeeasilyautomated(CMS,blog,..)willbe
eventually.Whatcannotneedstobecustommade.
Sowebdeveloperschangedthemselvesbyspecializingandconcentratingonwhatcannot
beautomatedsoeasily:webapplications.AlongwiththiscameanewmindsetonhowPHP
developmentshouldbedoneandwhattoolsshouldbeused.
10pillarsofmodernPHP
development
Weoftenreceiverequestsonhowtodesignapplicationsforourhostinginfrastructure.While
thereareathousanddifferentusecases,manydeservingofadifferentapproach,the
followingisbasedonourexperienceandshouldbeviewedasaguideline.
Manypeopleareusingmodernfullstackframeworks,suchasLaravel5,CakePHP
3,Symfony2orthelike.Thosealreadycomewithasetofstyleguides,patternsand
recommendations.
HowevermuchisstilluptothedevelopersohereareourtwocentsonhowacurrentPHP
applicationdevelopmentshouldbeapproached.
1.Code
Themostimportantpartofyourapplication.
Management
Thecodeshouldbeunderversioncontrol.WegoastepfurtherandstronglyrecommendGit
duetoit'swidespreadandavailabilityacrosstheboard(andbecausewearenotawareof
trulysuperioralternatives).
Style
Adheringtodefinedcodingstandardswillpayout:consistentcodeisbetter
comprehendablebyothermembersofateamandtherebyaddingnewmembersiseasier.
Nomatterthesizeoftheteam(evenforsingledevelopers):codemaintenancecaneasily
takeupthemajorityofaprojectstime(thusmoney)andwellformattedanddocumented
codeistheprimaryfactorinreducingthoseefforts.
Alsoit'sjustplainsatisfyingtoreadgoodcode.
Opensourcing
Opensourcingyourapplicationcode(oratleastmodularizedpartsofit)canbeanextremely
goodidea:freehandstohardenthecodequality,freemarketingforyourselforyour
companyandsupportingthecommunityasawhole.
Again,we'dliketoputanemphasisonGit.Usinganexoticrevisioncontrolitcouldbehard
tofinddeveloperswhicharewillingtosparetheextratime.
Thebeforementionedstylewillalsoimpactthelevelofacceptanceandwillingnessto
participate:usingexistingstandardshelpsallowsnewcomerstojumprightinwithoutwasting
timeondecipheringyourintentions.
2.Tests
AutomatedtestinghaslongbeentheblacksheepofthePHPfamily.However,thishas
greatlychangedthelegenditwoulddoubledevelopmenttimeisnearlyrootedoutandit's
now(luckilyand)virtuallyunthinkabletocontributeanythingtomostopensourceprojects
withoutacorrespondingtest.
Athoroughlytestedapplicationbringsalotofadvantages.Mypersonaltopthree:
Testedsoftwarecanbefareasierrefactored
Unittestingenforcesmodulardesign(increasedreusability)
Testsprovideadocumentationandexamplecode
Therearelotsofbenefitsbutintheendformeitboilsdowntothis:Bettercodeless
headache.
3.Dependencies
Dependenciesshould(ofcourse)behandledwithComposer.Sincethecodeisstrongly
coupledwithspecificpackage/librarythedependencydeclaration(composer.lock)shouldbe
intheversioncontrolaswell(inmyopinion).
Theactualpackage/libraryfiles(vendorfolder)shouldnotbepartofversioncontrol,since
theirrevisionsarealreadyhandledbythedeclaration,whichistherebyunderversioncontrol
anditwouldberedundanttodoboth.
Modularization
Beingauseroflibraries/packagesalsochangesyourmindset(oratleastpositivelyre
enforcesit)towardsmodularizationofyourowncode.Thisinturnleadstolesscode
repetitionacrossprojectsandtherebyreduceseffortandincreasesqualityinthelongterm.
Andlet'snotforgettheabilitytoopensourcethosemodules,asmentionedabove.
4.Configuration
Configuration,ifbadlyused,canbeagreathindrancewhenmigratingyourapplication.More
so,itcanbeasecurityrisk.
Separateconfigfromcode
Usingtheenvironmentisdefinitelythebestchoice.Bythisweprimarilymean(operating
system)environmentvariablesbutwethinklocalconfigurationfiles(oracombination
thereof)areavalidchoiceaswellaslongastheirdeploymentisclearlydefined.
Thebestruleofthumbtomeasurewhethertheconfigurationiscleanlyseparatedfromthe
codeweheardis:Couldyouopensourceyourcodewithoutexposinganycredentialsright
now?IftheanswerisYes,thenyouaregood.
Bad:insomeconfig.inc.php:
$database="foobar";
$user="foobar";
$password="foobar";
Good:EnvironmentvariablesfromApacheSetEnvorthelike:
//$_SERVER["DB_NAME"];
//$_SERVER["DB_USER"];
//$_SERVER["DB_PASSWORD"];
Complexconfig
Environmentvariablescancontaincomplexinformation(think:multilevelarray).Itshouldbe
marshaledasJSONandencodedintobase64soitiseasilymodifiableandreadablefrom
outsidetheapplication.
//somewhereinthebootstrap,assumingallencodedvariablesareprefixedwith"::"..
foreach($_SERVERas$k=>$v){
if(0===strpos($v,"::")){
$_SERVER[$k]=json_decode(base64_decode(substr($v,2)));
}
}
5.Assets
Assetdata,suchas(compiled)CSS,Javascript,imagesandsoon,aretrulyhardtodecide
upon.Inshortandwithlimitationsmyrecommendationistokeepthemunderversion
control.
Atlength:CompilationofCSSandJavascriptorcreatingmodifiedinstancesofimages
requiresasurprisinglylargeanddiversetoolsetwhichcomeswithalargedependencyset
oftheirown(thinkccompilerfornodeextensionwhichshrinksimagesusingimagemagick
bindingsvscompleteJavaruntimeforsomeCSScompilersvs..).Thisincreasesthe
complexityofthedeploymentinfrastructureunnecessarily.Thenthereistheresponsibility
problem:Assetsareoftenhandledbythefrontenddevelopersoftheteam.Asallspecialized
developers,theyhavetheirtoolswhichworkgreatforthem.Forcingassetcompilationinthe
releasecyclemeanstheyneedtolimitthemselvestothetoolsavailablehere.
ForatrulyindepthdiscussionaboutthistopicpleaseseeFrank'spreviousarticle.
6.Runtimedata
Runtimedataincludesallfilebaseddata(i.e.nodatabases),whichisgeneratedatruntime
byuserinteraction(egfileuploads)orasanresultthereof(egmultipleinstancesofan
image).Classicallythisishandledusingalocalornetworkattachedfilesystem(see
alsoflysystem).
Werecommendcloudstorages(suchasS3,CloudFiles,CloudStorage,..),sincethey:
inherentlysolvevariousscalabilityissues(scalingapplicationoutovermultipleserversor
geographicalregions),preventfuturemigrationheadaches(datalockin),nativelybalance
loadbyseparatingexecution(PHPscripts)anddelivery(staticfiles).
7.Resources
Resourcesareallserviceswhichareusedbytheapplication,suchasdatabases,caches,
queues,theaforementionedstorages,maildeliveryprovidersandallthat.
Abstraction
Accesstoresourcesshouldbeabstracted.Thedegreeofabstractionshoulddependon
probability(egifyouareplaningtoscaleoutthenyou'duseanadapterforalocalresource,
whichlaterwillbereplacedbyanadapterforanetworkcapableresource)andfeasibility(eg
acacheabstractionisalmostalwayssimple,whileanabstractionallowingtosubstitutea
MySQLdatabasewith,say,ElasticSearchmuchmoreeffort,egusingtherepositorypattern,
andthiseffortmustbejustifiable).
Thelocationofresourcesmustbesubstitutablebyconfiguration(asdescribedabove).
Bad:
$conn=newmysqli($servername,$username,$password);
ThecodewillbetightlycoupledtoMySQLdatabaseswithaspecificdriver.IfeitherMySQL
databasesorthisdriverisnotavailableinanewenvironmentthecodemustberefactored.
Good:
useIlluminate\Database\Capsule\Manager;
//$_SERVER['DATABASE']=["host"=>"localhost",...]
$mgr=newManager>addConnection($_SERVER['DATABASE']);
UsingadifferentSQLdatabasecaneasilybeachieved.UsingadifferentMySQLdatabase
locationcanbeeasilyconfigured.
Weakcoupling
All"soft"services,withoutwhichtheapplicationstillcanrun(egadatabasedriven
applicationcouldnotrunwithoutthedatabase)shouldbedisengageableeasily.Sayamail
serviceisusedtogreetnewuserswithawelcomemail:makesureyoucanswitchitoffwith
withasinglecommand,incasethemailprovidertemporarilygoesdown.Evenbetter:
automatethat.Best:Useaqueuewhichcanbackoffandretrybyitself.
8.Deployment
Inawebapplicationproject,therearefewthingsmorefeared,moredisasterproneand
henceoverandoverdelayedthanbigupgradesintoproduction.Deployearlyanddeploy
oftencircumventsthisbycontinuousintegrationofsmallupgrades.Theprimaryrequirement
toallowthisisasimple,transparentandfastdeployment.
WearehugefansofGitbaseddeployment,sinceitalreadycomeswithahistoryandallows
easyintegrationofbuildscripts.However,applicationneedsandenvironmentsdiffergreatly,
sotheperfectdeploymentforallsituationsisprobablynottofind.
Goodcodequality,testingandgoodmeasuredabstractionpayoutinthelongrun,havinga
easytousedeploymentworkflowisessentialforthedayin,dayoutwork.
9.Stages
Whileautomatedtestingprovidesagoodfoundation,whencodemeetscontentthereisstill
lot'sofroomformishaps.Hencethereistheconceptofstaging.Havinga(working)local
setupoftheapplicationalreadyprovidesthefirststage:thedevelopmentstage(orlocal
stage).Theotherstage,whichalwaysexists,isofcoursetheproductionstage:theliveweb
application.Nowthereislot'sofspaceinbetweenfortesting,reviewandwhatnot.
Ingeneral,allstagesshouldtrytoapproximatetheproductionenvironmentascloselyas
possible.Themoretheydeviate,thelesssensetheymake.
Howmanystagesshouldbeuseddependsonprojectsize,teamsize,teamsetup,kindof
applicationandsoon.Pleasereadamorecomprehensivediscussionhere.Asageneralrule
ofthumbwerecommendthreestages:Alocaldevelopmentstage,ofcoursetheproduction
stageandatestingstageinthesameenvironmentasproduction(ofcourse:separated).
10.Scalability
YouprobablyhaveheardthatyouarenowaDevOp.Thismeans:whenwritingyour
application,youmustbeawareoftheunderlyinginfrastructuresoyoudon'tfightwithit's
weaknesses,butratherleverageit'sstrength.
It'sabitofasideeffectofthecloudinfrastructure.Before:allyouhadtodo(andoftencould
do)wasverticallyscalingyourmachine:biggerserver.Soyouwouldnotcareasmuch
wherethebottleneckwas,sincetherewasonlyonesolution.Nowthatyoucannotonly
scaleout(horizontally),butdothatforeveryresourceindividually,youshouldknowwhich
oneslowsyoudown.Orwhatyoucandointermsofapplicationdesigntocompensatefor
that.Orespecially:whichnewresourceyoucanattachtoboosttheperformance.
Inshort:Yougotaccesstotheredbuttonandwithgreatpowercomesgreatresponsibility.
Summary
It'shardernow:Youmustknowmoreaboutcodingpatterns,deploymentstrategies,testing
andapplicationdesignthaneverbefore.It'seasiernow:afleetofnewtools,betterservices
andcodingstandardshelpandsupportasneverbefore.
TheartofwritingPHPcodehaschanged.Alot.Andwethinkitsnow
moreinterestingthanever.