Tải bản đầy đủ (.pdf) (371 trang)

Modern PHP Document PHP Offical Site

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (2.31 MB, 371 trang )

www.it-ebooks.info


ModernPHP
NewFeaturesandGoodPractices
JoshLockhart

www.it-ebooks.info


ModernPHP
byJoshLockhart
Copyright©2015JoshLockhart.Allrightsreserved.
PrintedintheUnitedStatesofAmerica.
PublishedbyO’ReillyMedia,Inc.,1005GravensteinHighwayNorth,Sebastopol,CA
95472.
O’Reillybooksmaybepurchasedforeducational,business,orsalespromotionaluse.
Onlineeditionsarealsoavailableformosttitles().Formore
information,contactourcorporate/institutionalsalesdepartment:800-998-9938or

Editor:AllysonMacDonald
ProductionEditor:NicoleShelby
Copyeditor:PhilDangler
Proofreader:EileenCohen
Indexer:JudyMcConville
InteriorDesigner:DavidFutato
CoverDesigner:EllieVolckhausen
Illustrator:RebeccaDemarest
February2015:FirstEdition

www.it-ebooks.info




RevisionHistoryfortheFirstEdition
2015-02-09:FirstRelease
Seeforreleasedetails.
TheO’ReillylogoisaregisteredtrademarkofO’ReillyMedia,Inc.ModernPHP,the
coverimage,andrelatedtradedressaretrademarksofO’ReillyMedia,Inc.
Whilethepublisherandtheauthorhaveusedgoodfaitheffortstoensurethatthe
informationandinstructionscontainedinthisworkareaccurate,thepublisherandthe
authordisclaimallresponsibilityforerrorsoromissions,includingwithoutlimitation
responsibilityfordamagesresultingfromtheuseoforrelianceonthiswork.Useofthe
informationandinstructionscontainedinthisworkisatyourownrisk.Ifanycode
samplesorothertechnologythisworkcontainsordescribesissubjecttoopensource
licensesortheintellectualpropertyrightsofothers,itisyourresponsibilitytoensurethat
yourusethereofcomplieswithsuchlicensesand/orrights.
978-1-491-90501-2
[LSI]

www.it-ebooks.info



ForLaurel

www.it-ebooks.info


Preface
ThereareamillionPHPtutorialsonline.Mostofthesetutorialsareoutdatedand
demonstrateobsoletepractices.Unfortunately,thesetutorialsarestillreferencedtoday

thankstotheirGoogleimmortality.OutdatedinformationisdangeroustounawarePHP
programmerswhounknowinglycreateslowandinsecurePHPapplications.Irecognized
thisissuein2013,anditistheprimaryreasonIbeganPHPTheRightWay,acommunity
initiativetoprovidePHPprogrammerseasyaccesstohigh-qualityandup-to-date
informationfromauthoritativemembersofthePHPcommunity.
ModernPHPismynextendeavortowardthesamegoal.Thisbookisnotareference
manual.Nope.Thisbookisafriendlyandfunconversationbetweenyouandme.I’ll
introduceyoutothemodernPHPprogramminglanguage.I’llshowyouthelatestPHP
techniquesthatIuseeverydayatworkandonmyopensourceprojects.AndI’llhelpyou
usethelatestcodingstandardssoyoucanshareyourPHPcomponentsandlibrarieswith
thePHPcommunity.
You’llhearmesay“community”overandover(andover).ThePHPcommunityis
friendlyandhelpfulandwelcoming—althoughnotwithoutoccasionaldrama.Ifyou
becomecuriousaboutaspecificfeaturementionedinthisbook,reachouttoyourlocal
PHPusergroupwithquestions.IguaranteeyoutherearenearbyPHPdeveloperswho
wouldlovetohelpyoubecomeabetterPHPprogrammer.YourlocalPHPusergroupisan
invaluableresourceasyoucontinuetoimproveyourPHPskillslongafteryoufinishthis
book.

www.it-ebooks.info


WhatYouNeedtoKnowAboutThisBook
Beforewegetstarted,Iwanttosetafewexpectations.First,itisimpossibleformeto
covereverywaytousePHP.Thereisn’tenoughtime.Instead,IwillshowyouhowIuse
PHP.Yes,thisisanopinionatedapproach,butIusetheverysamepracticesandstandards
adoptedbymanyotherPHPdevelopers.Whatyoutakeawayfromourbriefconversation
willbeimmediatelyapplicableinyourownprojects.
Second,Iassumeyouarefamiliarwithvariables,conditionals,loops,andsoon;youdon’t
havetoknowPHP,butyoushouldatleastbringabasicunderstandingofthese

fundamentalprogrammingconcepts.Youcanalsobringcoffee(Ilovecoffee).I’llsupply
everythingelse.
Third,Idonotassumeyouareusingaspecificoperatingsystem.However,mycode
examplesarewrittenforLinux.BashcommandsareprovidedforUbuntuandCentOSand
mayalsoworkonOSX.IfyouuseWindows,IhighlyrecommendyouspinupaLinux
virtualmachinesoyoucanruntheexamplecodeinthisbook.

www.it-ebooks.info


HowThisBookIsOrganized
PartIdemonstratesnewPHPfeatureslikenamespaces,generators,andtraits.Itintroduces
youtothemodernPHPlanguage,anditexposesyoutofeaturesyoumaynothaveknown
aboutuntilnow.
PartIIexploresgoodpracticesthatyoushouldimplementinyourPHPapplications.Have
youheardthetermPSR,butyou’renotentirelysurewhatitisorhowtouseit?Doyou
wanttolearnhowtosanitizeuserinputandusesafedatabasequeries?Thischapterisfor
you.
PartIIIismoretechnicalthanthefirsttwoparts.Itdemonstrateshowtodeploy,tune,test,
andprofilePHPapplications.WediveintodeploymentstrategieswithCapistrano.Wetalk
abouttestingtoolslikePHPUnitandTravisCI.AndweexplorehowtotunePHPsoit
performsaswellaspossibleforyourapplication.
AppendixAprovidesstep-by-stepinstructionsforinstallingandconfiguringPHP-FPMon
yourmachine.
AppendixBexplainshowtobuildalocaldevelopmentenvironmentthatcloselymatches
yourproductionserver.WeexploreVagrant,Puppet,Chef,andalternativetoolstohelp
yougetstartedquickly.

www.it-ebooks.info



ConventionsUsedinThisBook
Thefollowingtypographicalconventionsareusedinthisbook:
Italic
Indicatesnewterms,URLs,emailaddresses,filenames,andfileextensions.
Constantwidth

Usedforprogramlistings,aswellaswithinparagraphstorefertoprogramelements
suchasvariableorfunctionnames,databases,datatypes,environmentvariables,
statements,andkeywords.
Constantwidthbold

Showscommandsorothertextthatshouldbetypedliterallybytheuser.
Constantwidthitalic

Showstextthatshouldbereplacedwithuser-suppliedvaluesorbyvaluesdetermined
bycontext.
Tip
Thiselementsignifiesatiporsuggestion.
Note
Thiselementsignifiesageneralnote.
Warning
Thiselementindicatesawarningorcaution.

www.it-ebooks.info


UsingCodeExamples
Supplementalmaterial(codeexamples,exercises,etc.)isavailablefordownloadat
/>Thisbookisheretohelpyougetyourjobdone.Ingeneral,ifexamplecodeisoffered

withthisbook,youmayuseitinyourprogramsanddocumentation.Youdonotneedto
contactusforpermissionunlessyou’rereproducingasignificantportionofthecode.For
example,writingaprogramthatusesseveralchunksofcodefromthisbookdoesnot
requirepermission.SellingordistributingaCD-ROMofexamplesfromO’Reillybooks
doesrequirepermission.Answeringaquestionbycitingthisbookandquotingexample
codedoesnotrequirepermission.Incorporatingasignificantamountofexamplecode
fromthisbookintoyourproduct’sdocumentationdoesrequirepermission.
Weappreciate,butdonotrequire,attribution.Anattributionusuallyincludesthetitle,
author,publisher,andISBN.Forexample:“ModernPHPbyJoshLockhart(O’Reilly).
Copyright2015JoshLockhart,978-1-491-90501-2.”
Ifyoufeelyouruseofcodeexamplesfallsoutsidefairuseorthepermissiongivenabove,
feelfreetocontactusat

www.it-ebooks.info


Safari®BooksOnline
Note
SafariBooksOnlineisanon-demanddigitallibrarythatdeliversexpertcontentinboth
bookandvideoformfromtheworld’sleadingauthorsintechnologyandbusiness.
Technologyprofessionals,softwaredevelopers,webdesigners,andbusinessandcreative
professionalsuseSafariBooksOnlineastheirprimaryresourceforresearch,problem
solving,learning,andcertificationtraining.
SafariBooksOnlineoffersarangeofplansandpricingforenterprise,government,
education,andindividuals.
Membershaveaccesstothousandsofbooks,trainingvideos,andprepublication
manuscriptsinonefullysearchabledatabasefrompublisherslikeO’ReillyMedia,
PrenticeHallProfessional,Addison-WesleyProfessional,MicrosoftPress,Sams,Que,
PeachpitPress,FocalPress,CiscoPress,JohnWiley&Sons,Syngress,Morgan
Kaufmann,IBMRedbooks,Packt,AdobePress,FTPress,Apress,Manning,NewRiders,

McGraw-Hill,Jones&Bartlett,CourseTechnology,andhundredsmore.Formore
informationaboutSafariBooksOnline,pleasevisitusonline.

www.it-ebooks.info


HowtoContactUs
Pleaseaddresscommentsandquestionsconcerningthisbooktothepublisher:
O’ReillyMedia,Inc.
1005GravensteinHighwayNorth
Sebastopol,CA95472
800-998-9938(intheUnitedStatesorCanada)
707-829-0515(internationalorlocal)
707-829-0104(fax)
Wehaveawebpageforthisbook,wherewelisterrata,examples,andanyadditional
information.Youcanaccessthispageat />Tocommentorasktechnicalquestionsaboutthisbook,sendemailto

Formoreinformationaboutourbooks,courses,conferences,andnews,seeourwebsiteat
.
FindusonFacebook: />FollowusonTwitter: />WatchusonYouTube: />
www.it-ebooks.info


Acknowledgments
Thisismyfirstbook.WhenO’ReillyapproachedmeaboutwritingModernPHP,Iwas
equallyexcitedandscaredtodeath.ThefirstthingIdidwasaWalterHustondance;I
mean,O’Reillywantedmetowriteabook.Howcoolisthat!?ThenIaskedmyselfcanI
reallywritethatmanypages?Abookisn’taquickorsmalltask.
Ofcourse,Iimmediatelysaid“yes.”IknewIcouldwriteModernPHPbecauseIhad
family,friends,coworkers,editors,andreviewerssupportingmetheentireway.Iwantto

acknowledgeandthankmysupportersfortheirinvaluablefeedback.Withoutthem,this
bookwouldneverhavehappened.
First,IwanttothankmyeditoratO’ReillyMedia—AllysonMacDonald
(@allyatoreilly).Allywasnice,critical,supportive,andsmart.Sheknewexactlyhowand
whentogentlynudgemeintherightdirectionwheneverIgotofftrack.Ican’timagine
workingwithabettereditor.
Ialsowanttothankmytechnicalreviewers—AdamFairholm(@adamfairholm)andEd
Finkler(@funkatron).AdamisabrilliantwebdeveloperatNewfangled,andheisperhaps
bestknownforhisworkonIMVDb—thepopularmusicvideodatabase.EdiswellknownthroughoutthePHPcommunityforhisincrediblePHPskills,hispersonalityonthe
/dev/hellpodcast,andhiscommendableOpenSourcingMentalIllnesscampaign.Adam
andEdbothpointedouteverythingdumb,illogical,andincorrectinmyearlydrafts.This
bookisfarbetterthananythingIcouldwriteonmyownthankstotheirbrutallyhonest
feedback.Iamforeverindebtedtothemfortheirguidanceandwisdom.Ifanyfaultsor
inaccuracieswriggledtheirwayintothefinalmanuscript,thosefaultsaresurelymyown.
MycoworkersatNewMediaCampaignshavebeenaconstantsourceofencouragement.
Joel,Clay,Kris,Alex,Patrick,Ashley,Lenny,Claire,Todd,Pascale,Henry,andNathan
—Itipmyhattoallofyouforyourkindwordsofencouragementfrombeginningtoend.
Andmostimportant,Iwanttothankmyfamily—Laurel,Ethan,Tessa,Charlie,Lisa,
Glenn,andLiz.Thankyouforyourencouragement,withoutwhichIwouldhavenever
finishedthisbook.Tomylovelywife,Laurel,thankyouforyourpatience.Thankyoufor
accompanyingmetoCaribouCoffeeforsomanylate-nightwritingsessions.Thankyou
forlettingmeabandonyouonweekends.Thankyouforkeepingmemotivatedandon
schedule.Iloveyounowandforever.

www.it-ebooks.info


PartI.LanguageFeatures

www.it-ebooks.info



Chapter1.TheNewPHP
ThePHPlanguageisexperiencingarenaissance.PHPistransformingintoamodern
scriptinglanguagewithhelpfulfeatureslikenamespaces,traits,closures,andabuilt-in
opcodecache.ThemodernPHPecosystemisevolving,too.PHPdevelopersrelylesson
monolithicframeworksandmoreonsmallerspecializedcomponents.TheComposer
dependencymanagerisrevolutionizinghowwebuildPHPapplications;itemancipatesus
fromaframework’swalledgardenandletsusmixandmatchinteroperablePHP
componentsbestsuitedforourcustomPHPapplications.Componentinteroperability
wouldnotbepossiblewithoutcommunitystandardsproposedandcuratedbythePHP
FrameworkInteropGroup.
ModernPHPisyourguidetothenewPHP,anditwillshowyouhowtobuildanddeploy
amazingPHPapplicationsusingcommunitystandards,goodpractices,andinteroperable
components.

www.it-ebooks.info


Past
BeforeweexploremodernPHP,itisimportanttounderstandPHP’sorigin.PHPisan
interpretedserver-sidescriptinglanguage.ThismeansyouwritePHPcode,uploadittoa
webserver,andexecuteitwithaninterpreter.PHPistypicallyusedwithawebserverlike
Apacheornginxtoservedynamiccontent.However,PHPcanalsobeusedtobuild
powerfulcommand-lineapplications(justlikebash,Ruby,Python,andsoon).ManyPHP
developersdon’trealizethisandmissoutonareallyexcitingfeature.Notyou,though.
YoucanreadtheofficialPHPhistoryatIwon’t
repeatwhathasalreadybeensaidsowellbyRasmusLerdorf(thecreatorofPHP).WhatI
willtellyouisthatPHPhasatumultuouspast.PHPbeganasacollectionofCGIscripts
writtenbyRasmusLerdorftotrackvisitstohisonlineresume.Lerdorfnamedhissetof

CGIscripts“PersonalHomePageTools.”Thisearlyincarnationwascompletelydifferent
fromthePHPweknowtoday.Lerdorf’searlyPHPToolswerenotascriptinglanguage;
theyweretoolsthatprovidedrudimentaryvariablesandautomaticformvariable
interpretationusinganHTMLembeddedsyntax.
Between1994and1998,PHPunderwentnumerousrevisionsandevenreceivedafew
ground-uprewrites.AndiGutmansandZeevSuraski,twodevelopersfromTelAviv,
joinedforceswithRasmusLerdorftotransformPHPfromasmallcollectionofCGItools
intoafull-fledgedprogramminglanguagewithamoreconsistentsyntaxandbasicsupport
forobject-orientedprogramming.TheynamedtheirfinalproductPHP3andreleaseditin
late1998.ThenewPHPmonikerwasadeparturefromearliernames,anditisarecursive
acronymforPHP:HypertextPreprocessor.PHP3wasthefirstversionthatmost
resembledthePHPweknowtoday.Itprovidedsuperiorextensibilitytovariousdatabases,
protocols,andAPIs.PHP3’sextensibilityattractedmanynewdeveloperstotheproject.
Bylate1998,PHP3wasalreadyinstalledonastaggering10%oftheworld’swebservers.

www.it-ebooks.info


Present
Today,thePHPlanguageisquicklyevolvingandissupportedbydozensofcoreteam
developersfromaroundtheworld.Developmentpracticeshavechanged,too.Inthepast,
itwascommonpracticetowriteaPHPfile,uploadittoaproductionserverwithFTP,and
hopeitworked.Thisisaterribledevelopmentstrategy,butitwasnecessaryduetoalack
ofviablelocaldevelopmentenvironments.
Nowadays,weeschewFTPanduseversioncontrolinstead.Versioncontrolsoftwarelike
Githelpsmaintainanauditablecodehistorythatcanbebranched,forked,andmerged.
Localdevelopmentenvironmentsareidenticaltoproductionserversthanksto
virtualizationtoolslikeVagrantandprovisioningtoolslikeAnsible,Chef,andPuppet.We
leveragespecializedPHPcomponentswiththeComposerdependencymanager.OurPHP
codeadherestoPSRs—communitystandardsmanagedbythePHPFrameworkInterop

Group.WethoroughlytestourcodewithtoolslikePHPUnit.Wedeployourapplications
withPHP’sFastCGIprocessmanagerbehindawebserverlikenginx.Andweincrease
applicationperformancewithanopcodecache.
ModernPHPencompassesmanynewpracticesthatmaybeunfamiliartothoseofyounew
toPHP,ortothoseupgradingfromolderPHPversions.Don’tfeeloverwhelmed.I’llwalk
througheachconceptlaterinthisbook.
I’malsoexcitedthatPHPnowhasanofficialdraftspecification—somethingitlacked
until2014.
Note
Mostmatureprogramminglanguageshaveaspecification.Inlayman’sterms,a
specificationisacanonicalblueprintthatdefineswhatitmeanstobePHP.Thisblueprint
isusedbydeveloperswhocreateprogramsthatparse,interpret,andexecutePHPcode.It
isnotfordeveloperswhocreateapplicationsandwebsiteswithPHP.
SaraGolemonandFacebookannouncedthefirstPHPspecificationdraftatO’Reilly’s
OSCONconferencein2014.YoucanreadtheofficialannouncementonthePHPinternals
mailinglist,andyoucanreadthePHPspecificationonGitHub.
AnofficialPHPlanguagespecificationisbecomingmoreimportantgiventheintroduction
ofmultiplecompetingPHPengines.TheoriginalPHPengineistheZendEngine,aPHP
interpreterwritteninCandintroducedinPHP4.TheZendEnginewascreatedbyRasmus
Lerdorf,AndiGutmans,andZeevSuraski.TodaytheZendEngineistheZendcompany’s
maincontributiontothePHPcommunity.However,thereisnowasecondmajorPHP
engine—theHipHopVirtualMachinefromFacebook.Alanguagespecificationensures
thatbothenginesmaintainabaselinecompatibility.
Note
APHPengineisaprogramthatparses,interprets,andexecutesPHPcode(e.g.,theZend
EngineorFacebook’sHipHopVirtualMachine).ThisisnottobeconfusedwithPHP,
whichisagenericreferencetothePHPlanguage.

www.it-ebooks.info



Future
TheZendEngineisimprovingatarapidpacewithnewfeaturesandimproved
performance.IattributetheZendEngine’simprovementstoitsnewcompetition,
specificallyFacebook’sHipHopVirtualMachineandHackprogramminglanguage.
HackisanewprogramminglanguagebuiltontopofPHP.Itintroducesstatictyping,new
datastructures,andadditionalinterfaceswhilemaintainingbackwardcompatibilitywith
existingdynamicallytypedPHPcode.Hackistargetedatdeveloperswhoappreciate
PHP’srapiddevelopmentcharacteristicsbutneedthepredictabilityandstabilityfrom
statictyping.
Note
We’lldiscussdynamicversusstatictypinglaterinthisbook.Thedifferencebetweenthe
twoiswhenPHPtypesarechecked.Dynamictypesarecheckedatruntime,whereasstatic
typesarecheckedatcompiletime.JumpaheadtoChapter12formoreinformation.
TheHipHopVirtualMachine(HHVM)isaPHPandHackinterpreterthatusesajustin
time(JIT)compilertoimproveapplicationperformanceandreducememoryusage.
Idon’tforeseeHackandHHVMreplacingtheZendEngine,butFacebook’snew
contributionsarecreatingagiantsplashinthePHPcommunity.Increasingcompetition
haspromptedtheZendEnginecoreteamtoannouncePHP7,anoptimizedZendEngine
saidtobeonparwithHHVM.We’lldiscussthesedevelopmentsfurtherinChapter12.
It’sanexcitingtimetobeaPHPprogrammer.ThePHPcommunityhasneverbeenthis
energized,fun,andinnovative.IhopethisbookhelpsyoufirmlyembracemodernPHP
practices.Thereareatonofnewthingstolearn,andmanymorethingsonthehorizon.
Considerthisyourroadmap.Nowlet’sgetstarted.

www.it-ebooks.info


Chapter2.Features
ThemodernPHPlanguagehasmanyexcitingnewfeatures.Manyofthesefeatureswillbe

brandnewtoPHPprogrammersupgradingfromearlierversions,andthey’llbeanice
surprisetoprogrammersmigratingtoPHPfromanotherlanguage.Thesenewfeatures
makethePHPlanguageapowerfulplatformandprovideapleasantexperiencefor
buildingwebapplicationsandcommand-linetools.
Someofthesefeaturesaren’tessential,buttheystillmakeourliveseasier.Somefeatures,
however,areessential.Namespaces,forexample,areacornerstoneofmodernPHP
standardsandenabledevelopmentpracticesthatmodernPHPdeveloperstakeforgranted
(e.g.,autoloading).I’llintroduceeachnewfeature,explainwhyitisuseful,andshowyou
howtoimplementitinyourownprojects.
Tip
Iencourageyoutofollowalongonyourowncomputer.Youcanfindallofthetext’scode
examplesinthisbook’scompanionGitHubrepository.

www.it-ebooks.info


Namespaces
IfthereisonemodernPHPfeatureIwantyoutoknow,itisnamespaces.Introducedin
PHP5.3.0,namespacesareanimportanttoolthatorganizesPHPcodeintoavirtual
hierarchy,comparabletoyouroperatingsystem’sfilesystemdirectorystructure.Each
modernPHPcomponentandframeworkorganizesitscodebeneathitsownglobally
uniquevendornamespacesothatitdoesnotconflictwith,orlayclaimto,commonclass
namesusedbyothervendors.
Note
Don’tyouhateitwhenyouwalkintoacoffeeshopandthisoneobnoxiouspersonhasa
messofbooks,cables,andwhatnotspreadacrossseveraltables?Nottomentionhe’s
sittingnextto,butnotusing,theonlyavailablepoweroutlet.He’swastingvaluablespace
thatcouldotherwisebeusefultoyou.Figurativelyspeaking,thispersonisnotusing
namespaces.Don’tbethisperson.
Let’sseehowareal-worldPHPcomponentusesnamespaces.TheSymfonyFramework’s

ownsymfony/httpfoundationisapopularPHPcomponentthatmanagesHTTPrequests
andresponses.Moreimportant,thesymfony/httpfoundationcomponentusescommon
PHPclassnameslikeRequest,Response,andCookie.Iguaranteeyoutherearemany
otherPHPcomponentsthatusethesesameclassnames.Howcanweusethe
symfony/httpfoundationPHPcomponentifotherPHPcodeusesthesameclassnames?
Wecansafelyusethesymfony/httpfoundationcomponentpreciselybecauseitscodeis
sandboxedbeneaththeuniqueSymfonyvendornamespace.Visitthe
symfony/httpfoundationcomponentonGitHubandnavigatetotheResponse.phpfile.It
lookslikeFigure2-1.

Figure2-1.GitHubsymfony/httpfoundationscreenshot
Lookcloselyatline12.Itcontainsthiscode:
www.it-ebooks.info


namespaceSymfony\Component\HttpFoundation;

ThisisaPHPnamespacedeclaration,anditalwaysappearsonanewlineimmediately
aftertheopeningFirst,weknowtheResponseclasslivesbeneaththeSymfonyvendornamespace(the
vendornamespaceisthetopmostnamespace).WeknowtheResponseclasslivesbeneath
theComponentsubnamespace.WealsoknowtheResponseclasslivesbeneathyetanother
subnamespacenamedHttpFoundation.Youcanviewotherfilesadjacentto
Response.php,andyou’llseetheyusethesamenamespacedeclaration.Anamespace(or
subnamespace)encapsulatesandorganizesrelatedPHPclasses,justasafilesystem
directorycontainsrelatedfiles.
Tip
Subnamespacesareseparatedwitha\character.
Unlikeyouroperatingsystem’sphysicalfilesystem,PHPnamespacesareavirtualconcept
anddonotnecessarilymap1:1withfilesystemdirectories.Thatbeingsaid,mostPHP

componentsdo,infact,mapsubnamespacestofilesystemdirectoriesforcompatibility
withthepopularPSR-4autoloaderstandard(we’lltalkmoreaboutthisinChapter3).
Note
Technicallyspeaking,namespacesaremerelyaPHPlanguagenotationreferencedbythe
PHPinterpretertoapplyacommonnameprefixtoasetofclasses,interfaces,functions,
andconstants.

www.it-ebooks.info


WhyWeUseNamespaces
Namespacesareimportantbecausetheyletuscreatesandboxedcodethatworksalongside
otherdevelopers’code.ThisisthecornerstoneconceptofthemodernPHPcomponent
ecosystem.Componentandframeworkauthorsbuildanddistributecodeforalarge
numberofPHPdevelopers,andtheyhavenowayofknowingorcontrollingwhatclasses,
interfaces,functions,andconstantsareusedalongsidetheirowncode.Thisproblem
appliestoyourownin-houseprojects,too.IfyouwritecustomPHPcomponentsor
classesforaproject,thatcodemustworkalongsideyourproject’sthird-party
dependencies.
AsImentionedearlierwiththesymfony/httpfoundationcomponent,yourcodeand
otherdevelopers’codemightusethesameclass,interface,function,orconstantnames.
Withoutnamespaces,anamecollisioncausesPHPtofail.Withnamespaces,yourcode
andotherdevelopers’codecanusethesameclass,interface,function,orconstantname
assumingyourcodelivesbeneathauniquevendornamespace.
Ifyou’rebuildingatinypersonalprojectwithonlyafewdependencies,classname
collisionsprobablywon’tbeanissue.Butwhenyou’reworkingonateambuildingalarge
projectwithnumerousthird-partydependencies,namecollisionsbecomeaveryreal
concern.Youcannotcontrolwhichclasses,interfaces,functions,andconstantsare
introducedintotheglobalnamespacebyyourproject’sdependencies.Thisiswhy
namespacingyourcodeisimportant.


www.it-ebooks.info


Declaration
EveryPHPclass,interface,function,andconstantlivesbeneathanamespace(or
subnamespace).NamespacesaredeclaredatthetopofaPHPfileonanewline
immediatelyaftertheopeningnamespace,thenaspacecharacter,thenthenamespacename,andthenaclosing
semicolon;character.
Rememberthatnamespacesareoftenusedtoestablishatop-levelvendorname.This
examplenamespacedeclarationestablishestheOreillyvendorname:
namespaceOreilly;

AllPHPclasses,interfaces,functions,orconstantsdeclaredbeneaththisnamespace
declarationliveintheOreillynamespaceandare,insomeway,relatedtoO’Reilly
Media.Whatifwewantedtoorganizecoderelatedtothisbook?Weuseasubnamespace.
Subnamespacesaredeclaredexactlythesameasinthepreviousexample.Theonly
differenceisthatweseparatenamespaceandsubnamespacenameswiththe\character.
ThefollowingexampledeclaresasubnamespacenamedModernPHPthatlivesbeneaththe
topmostOreillyvendornamespace:
namespaceOreilly\ModernPHP;

Allclasses,interfaces,functions,andconstantsdeclaredbeneaththisnamespace
declarationliveintheOreilly\ModernPHPsubnamespaceandare,insomeway,relatedto
thisbook.
Allclassesinthesamenamespaceorsubnamespacedon’thavetobedeclaredinthesame
PHPfile.YoucanspecifyanamespaceorsubnamespaceatthetopofanyPHPfile,and

thatfile’scodebecomesapartofthatnamespaceorsubnamespace.Thismakesitpossible
towritemultipleclassesinseparatefilesthatbelongtoacommonnamespace.
Tip
Themostimportantnamespaceisthevendornamespace.Thisisthetopmostnamespace
thatidentifiesyourbrandororganization,anditmustbegloballyunique.Subnamespaces
arelessimportant,buttheyarehelpfulfororganizingyourproject’scode.

www.it-ebooks.info


ImportandAlias
Beforewehadnamespaces,PHPdeveloperssolvedthenamecollisionproblemwith
Zend-styleclassnames.Thiswasaclass-namingschemepopularizedbytheZend
FrameworkwherePHPclassnamesusedunderscoresinlieuoffilesystemdirectory
separators.Thisconventionaccomplishedtwothings:itensuredclassnameswereunique,
anditenabledanaiveautoloaderimplementationthatreplacedunderscoresinPHPclass
nameswithfilesystemdirectoryseparatorstodeterminetheclassfilepath.
Forexample,thePHPclass
Zend_Cloud_DocumentService_Adapter_WindowsAzure_QuerycorrespondstothePHP

fileZend/Cloud/DocumentService/Adapter/WindowsAzure/Query.php.Asideeffectofthe
Zend-stylenamingconvention,asyoucansee,isabsurdlylongclassnames.Callmelazy,
butthere’snowayI’mtypingthatclassnamemorethanonce.
ModernPHPnamespacespresentasimilarproblem.Forexample,thefullResponseclass
nameinthesymfony\httpfoundationcomponentis
\Symfony\Component\HttpFoundation\Response.Fortunately,PHPletsusimportand
aliasnamespacedcode.
Byimport,ImeanthatItellPHPwhichnamespaces,classes,interfaces,functions,and
constantsIwilluseineachPHPfile.Icanthenusethesewithouttypingtheirfull
namespaces.

Byalias,ImeanthatItellPHPthatIwillreferenceanimportedclass,interface,function,
orconstantwithashortername.
Tip
YoucanimportandaliasPHPclasses,interfaces,andothernamespacesasofPHP5.3.
YoucanimportandaliasPHPfunctionsandconstantsasofPHP5.6.
ThecodeshowninExample2-1createsandsendsa400BadRequestHTTPresponse
withoutimportingandaliasing.
Example2-1.Namespacewithoutalias
$response=new\Symfony\Component\HttpFoundation\Response('Oops',400);
$response->send();

Thisisn’tterrible,butimagineyouhavetoinstantiateaResponseinstanceseveraltimesin
asinglePHPfile.Yourfingerswillgettiredquickly.NowlookatExample2-2.Itdoesthe
samethingwithimporting.
Example2-2.Namespacewithdefaultalias
useSymfony\Component\HttpFoundation\Response;
$response=newResponse('Oops',400);
$response->send();

WetellPHPweintendtousetheSymfony\Component\HttpFoundation\Responseclass
withtheusekeyword.Wetypethelong,fullyqualifiedclassnameonce.Thenwecan
instantiatetheResponseclasswithoutusingitsfullynamespacedclassname.Howcoolis
www.it-ebooks.info


that?
SomedaysIfeelreallylazy.Thisisagoodopportunitytouseanalias.Let’sextend
Example2-2.InsteadoftypingResponse,maybeIjustwanttotypeResinstead.

Example2-3showshowIcandothat.
Example2-3.Namespacewithcustomalias
useSymfony\Component\HttpFoundation\ResponseasRes;
$r=newRes('Oops',400);
$r->send();

Inthisexample,IchangedtheimportlinetoimporttheResponseclass.Ialsoappended
asRestotheendoftheimportline;thistellsPHPtoconsiderResanaliasforthe
Responseclass.Ifwedon’tappendtheasResaliastotheimportline,PHPassumesa
defaultaliasthatisthesameastheimportedclassname.
Tip
YoushouldimportcodewiththeusekeywordatthetopofeachPHPfile,immediately
aftertheopeningYoudon’tneedaleading\characterwhenimportingcodewiththeusekeywordbecause
PHPassumesimportednamespacesarefullyqualified.
Theusekeywordmustexistintheglobalscope(i.e.,notinsideofaclassorfunction)
becauseitisusedatcompiletime.Itcan,however,belocatedbeneathanamespace
declarationtoimportcodeintoanothernamespace.
AsofPHP5.6,it’spossibletoimportfunctionsandconstants.Thisrequiresatweaktothe
usekeywordsyntax.Toimportafunction,changeusetousefunc:
usefuncNamespace\functionName;
functionName();

Toimportaconstant,changeusetouseconstant:
useconstantNamespace\CONST_NAME;
echoCONST_NAME;


Functionandconstantaliasesworkthesameasclasses.

www.it-ebooks.info


×