Romer M. - Web Development With Zend Framework 2 - 2013

download Romer M. - Web Development With Zend Framework 2 - 2013

If you can't read please download the document

Transcript of Romer M. - Web Development With Zend Framework 2 - 2013

Web Development with Zend Framework 2 Concepts, Techniques and Practical Solutions MichaelRomer Thisbookisforsaleathttp://leanpub.com/zendframework2-en Thisversionwaspublishedon2013-03-10 ThisisaLeanpubbook.LeanpubempowersauthorsandpublisherswiththeLeanPublishing process.LeanPublishingistheactofpublishinganin-progressebookusinglightweighttool sand manyiterationstogetreaderfeedback,pivotuntilyouhavetherightbookandbuildtractiono nce youdo.

2012-2013MichaelRomer

Contents Aboutthebook 1 EarlyAccessEdition...................................... 1 Thebook sonlinecommunity................................. 1 ImportantnoticeforAmazoncustomers ........................... 1 Introduction 2 Forwhomisthisbook?..................................... 2 You&I ............................................. 3 Structureofthisbook ..................................... 3 Repetitions ........................................... 4 Howyoucanbestworkwiththisbook............................ 4 Foundabug?.......................................... 4 Conventionsusedinthisbook................................. 5 ZendFramework2-Anoverview 6 HowFrameworkisbeingdeveloped.............................. 6 Modulesystem......................................... 7 Eventsystem.......................................... 9 MVCimplementation ..................................... 10 Additionalcomponents..................................... 11 DesignPatterns:Interface,Factory,Manager,etc. ...................... 13 Hello,ZendFramework2! 16 Installation ........................................... 16 ZendSkeletonApplication ................................... 17 Composer............................................ 17 Afirstsignoflife........................................ 19

DirectorystructureofaZendFramework2application ................... 20 Theindex.phpfile ....................................... 23

CONTENTS Preparingone sownmodule 28 Preparingthe HelloWorld module ............................. 28 Autoloading........................................... 34 OnetimeRequestandbackagain 40 ServiceManager......................................... 40 Writingaserviceofone sown................................. 44 ModuleManager ........................................ 50 Application........................................... 59 ViewManager.......................................... 62 Summary............................................ 64 EventManager 66 Registeringalistener...................................... 66 Registeringseverallistenersatthesametime......................... 67 Removingaregisteredlistener................................. 68 Triggeranevent ........................................ 69 SharedEventManager...................................... 70 Usingeventsinone sownclasses............................... 72 Modules 82 The Application module................................... 82 Module-dependentbehaviour................................. 84 Installingathird-partymodule ................................ 86 Configuringathird-partymodule............................... 88 Controller 92 Concept&modeofoperation................................. 92 Controllerplugins ....................................... 92 Writingone sowncontrollerplugin.............................. 98

CONTENTS Views 100 Concept&modeofoperation.................................100 Layouts.............................................102 Writingaviewhelperofone sown..............................103 Model 105 Entities,repositories&valueobjects .............................106 Businessservices&factories..................................108 Businessevents.........................................108 Routing 109 Introduction...........................................109 Definitionofroutes.......................................109 Matchingtest..........................................110 GenerationofaURL......................................117 Standardrouting........................................118 Creativerouting:A/Btests...................................120 Dependencyinjection 121 Introduction...........................................121 Zend\Diforobjectgraphs ...................................126 Zend\Diforconfigurationmanagement............................134 PersistencewithZend\Db 137 Connectingtodatabases....................................138 GeneratingandrunningSQL-Statements...........................140 Workingwithtablesandentries................................143 Organisationofdatabasequeries ...............................147 Zend\DBalternative:Doctrine2ORM ............................157 Validators 158 Standardvalidators.......................................158 Writingyourownvalidators..................................160

CONTENTS Webforms 162 Preparingaform........................................162 Displayingaform .......................................165 Editingformentries ......................................166 Validatingformentries.....................................167 Standardformelements ....................................174 Fleldsets.............................................176 LinkingentitieswithForms ..................................181 Developers Dairy 194 Introduction...........................................194 Envisioning...........................................194 Sprint1-CodeRepository,DevelopmentEnvironmentandtheinitialCodebase......194 Sprint2-Acustommodulewithaddproductfunctionality.................198 Sprint3-Addadeal,showavailabledeals..........................229 Sprint4-Orderform......................................253 Sprint5-MakeZfDealsavailableasaZF2module......................257 What snext? ..........................................267

About the book Early Access Edition Ifyouarereadingthissection,youareholdingthe earlyaccessedition ofthisbookinyourhands . Earlyaccess meansthatyoucanalreadybeginreadingthebookwhilethesubsequentchapters arestillbeingwritten.Theywillbemadeavailabletoyouassoonastheyarefinished.Thanks totheleanpublishingconcept,youarealsonowmuchmoreuptodatethanyouhaveeverbeen before.ThecontentsofthisbookrefertoVersion2.0ofFramework,theywillveryprobablyals o unconditionallyvalidtolaterversions.Itisverypossiblethatyoumightfindanumberofspe lling errorsoralsoabugortwointhecodeexamplesintheearlyaccessedition.Atthepresenttimeno onehassupportedmewithproofreadingoreditinginordertoreducethenumberoferrorsinthis booktoaminimum.Naturally,Iattempttobeworkascarefullyaspossible,butIcannotguarant ee absolutefreedomfromerrorsatthistime.Pleasebearwithme.Ifyouwouldliketohelpmeimpro ve thisbook,feelfreetoparticipateinthebook sonlinecommunityandletmeknowaboutyourideas oranyissuesyoudiscoverwithininthebook.Iwouldgreatlyappreciateit. The book s online community Foundabugwithinthebook?WanttotalkaboutthebookcontentsorZendFramework2ingeneral? Pleasefeelfreetojointhebook sonlinecommunity,theGoogle-Group WebDevelopmentwith ZendFramework2Book .YouwillneedaGoogleAccountwhichmaybesetupfreeofcharge. Important notice for Amazon customers IfyouboughtthisbookatAmazon,itiscurrentlysomewhatmoredifficulttoensurethatyou automaticallyreceiveallofitsupdatesastheyarepublished.Toavoidproblems,pleasesend ashort emailwith UpdatesZF2book [email protected], youcanbecertainthatyouwillreallyalwayshavethelatestversionofthebook.Asthanksfor youreffortsyouwillalsoadditionallyreceivethePDFandEPUBversionsofthebook. http://leanpub.com/

https://groups.google.com/forum/#!forum/web-development-with-zend-framework-2-boo k 1

Introduction ZendFramework2isanopensourceFrameworkforthedevelopmentofprofessionalwebapplicati onsforPHPVersion5.3. andhigher.Itisoperatedontheserverandisprimarilyusedtoproduce dynamicwebcontentsorconducttransactionssuchaspurchasingaproductinanonlineshop. Inthiscontext,ZendFramework2cansupportthedevelopmentofanytypeof(web)application becauseitprovidesuniversallyapplicablesolutionsthatcanbeusedinecommerce,content, communityorSaaSapplicationsequallywell.ZendFrameworkisessentiallybeingdevelopedb ythe ZendCompany,whichalsogaveFrameworkitsnameandprovidesitwithasold(financial)basis, notleastalsobecauseZenditselfisalsoinvolvedinthedevelopmentofthePHPprogramming language.However,inadditiontoZend,anumberofprestigiouscompaniesalsosupportZend Frameworkandareinterestedinitslong-termsuccess.AmongthemarealsoMicrosoftandIBM. AlloftheaboveprovidessecurityfortheselectionofZendFrameworkandalsomakesitsselect ion agooddecisionasthebasisforone sownapplicationfromaneconomicpointofview. ZendFrameworkinthestableVersion1.0firstappearedonthesceneon30/06/2007andhassince madealastingimpressiononthefaceofwebdevelopmentwithPHPOnecantrulysaythat programmingwithPHPalsofirstbecamereallyacceptableforapplicationscriticaltocompan ywith ZendFramework.Ifonepreviouslyputone strustincomplexJ2E(Java)applicationsincorporat e contexts,inthemeantimePHPandZendFrameworkaregladlychosenwithaclearconscience becausethiscombinationindeedprovidesabalancedratiooflightnessandprofessionalismt hat practicallynootherplatformcanachieve. IfonetakesthefirstpreviewreleasesofZendFramework1intoconsideration,todayFramewor kis alreadymorethan6yearsold.Evenifmuchhasbeenachievedintheinnumerablereleasesfrom thefirstpreviewuptothecurrentversion1.11,anumberofurgentlyneededimprovementsand extensionscouldnolongerbeimplementedontheoldcodebase;thisjustifiesanewmajorrelea se, whichisforthefirsttimenolongercompatibletoearlierversions.Itistimeforanewbeginni ng. ZendFramework2marksthenextmilestoneintheevolutionofthePHPwebframeworks,but alsoofPHPitself,forasonehasrecentlyseenontheexamplesofJavaandRuby,agood programminglanguagealoneisnotenoughtoalsobereallysuccessfulonabroaderfront.Only withframeworks suchasStruts,Spring,RailsorindeedalsoZendFramework thatarebasedon theprogramminglanguageandalsosignificantlyreducetheinitialdevelopmenteffortbutal so, long-termmaintenanceeffortofanapplication,doesawebdevelopmentplatformreallybecom e established. For whom is

this book? Itisachallengetowriteatechnicalbookwhichfindsabalancebetweentheoryandpracticeand allowsbothnovicesandprofessionalstogetthebestoutofthebook.Igladlyacceptedthistas k,but Ileftmyselfanescapehatch.IfIhavethefeelingthatwearegettinglostinaforestofdetails that 2

Introduction cannotbeexplainedingreaterdetailattherespectivelocationorevenentirelyinthisbook, Irefer thereadertopassageslateroninthebookortosecondaryliteraturesources. AfurtherchallengeiswhetherornotmyreadershaveanypreviousknowledgeofZendFramework. AdeveloperwhohasonlyjustbeguntoworkwithVersion2ofZendFrameworkrequiresdifferent informationinsomeplacesthanan oldhand ,quicklyfindshisorherwayaroundthemany cornersinVersion2becauseheorsheisalreadyfamiliarwithideasandconceptsfromVersion1 . ForallthosewhoarefamiliarwithVersion1,IwillfrequentlyrefertothepredecessorofVers ion2 atappropriateplaces wheneverIconsideritnecessary withoutgoingintoexcessivedetail.Tha t mightalsoperhapshelpnovices,becauseinthismannertheywouldgetabetterfeelingforwhy Version2isnecessary.ThisbookshouldbehelpfulforbothnovicesandadvancedlearnersofZe nd Framework. IpresumethatyouhavebasicknowledgeofPHP.YoudonothavetobeaPHPexpert,particularly becausemany native PHPfunctionsevenbecameobsoletewhenoneusedFramework,for example,SessionManagement,whichmapsinanobject-orientedmannerandinthismanner thankfullyabstractssomeofthelow-levelfunctionality. Hence,ifyouareaccustomedtoPHP syntax,haveabasicunderstandingoftheoperatingprinciplesofPHPapplicationsandarefam iliar withthecommonfunctionsofthelanguagecore,youarewellprepared.Ifnecessary,youwillal so havetouseaPHPhandbook. You & I Hi,IamMichael.Ihopethatyouwon tobjectifIoccasionallyusecontractionsandthelessforma l you insteadof one inmyexplanations.Thatmakeswritingiteasierformmeandensuresaless formalatmosphere. Structure of this book Thisbookisnotmeanttobeacompendium,butratherapragmaticandpractice-oriented introductiontothebasicconceptsandpracticalworkwithZendFramework2.Fromacertain pointinone sprogressasadeveloperonward,theofficialdocumentationservesasacompendium forexperienceddevelopers,butitisnotreallyappropriateforusewhileyouarebecomingfam iliar

withthesubject;instead,itservesasan(indispensible)referenceworkforfurtherdetaile dquestions afteronehasachievedtherequiredbasicunderstandingoftheprogram.Andexactlythatisthi s book sobjective. Itisstructuredsuchthatyoucanreaditfromthebeginningtotheend,andthatiswhatyoushoul d do.WewillbeginwithanoverviewofFrameworkandwillfirstlookattheessentialconceptsand ideaswhichmakeuptheessenceofFrameworkandalsodifferentiateitfromitspredecessors.O n theway,wewillrepeatedlyalsolooktotheleftandtotherightandthusbecomefamiliarwith someframeworkconditions,forexamplehowFrameworkwasreallydeveloped.Thenwewillgo

Introduction intomoredetailandelucidateFramework smostimportantcomponentsandrelationships;then takealookathowaHTTPrequestisprocessedandwriteourfirstbitofcode.Thisisfollowed byanexcursionintotheFrameworkenvironment.Wewillexaminethemostimportantmodules, whichhavebeenmadeavailablebythirdpartiesand,forexample,maketherealisationofauser administrationofone sownobsolete.AlargepartofthemagicofthenewFrameworkversionisthe resultofthemoduleconcept,andmodulescan aswewillseelater greatlyaccelerateandsimplify thedevelopmentofyourownapplications.Itistobeexpectedthatinashorttimealargenumber ofhigh-qualitymoduleswillbeavailableforZendFramework2. Lastbutnotleast,thereisanadditional,intensivepracticesectionintheformofa developer s diary . Wewilldevelopawebapplicationtogether,whichisalsointendedtoreallybeused subsequentlybyabusinessenterprise;forthisreasonitisbetterifwereallytryhard.Atthe latest, wewillbegindoingreal hands-on workatthispoint. Repetitions YouwillsoonrealisethatIfrequentlyexplaincontextsseveraltimesinthisbookThiscanbed ue totwothings:1)thatIlosttrackofwhatIhadalreadysaidandwhatIhadnot(:-D)or2)that Iconsciouslyintendedtodoit.ForeventheoldRomansknewthat:Repetitiomaterstudiorum est Repetitionisthemotheroflearning. Butalsothefactthattherespectivecontextsarein adifferentcontextineachcaseandthusdiscussedfromanotherperspectiveisalsoconducive to comprehension.Thus,ifyouhappentofindaplaceinthebookwhereyouthink, Ialreadyknow allthat! ,justbegladthatyouhavelearnedsomuchandcontinuereadingorjustskiptherespect ive passage. How you can best work with this book Programming(orhandlingaprogrammingframework)isbestlearnedwhenyoubecomeactive yourself.Indeed,particularlythefirstchapteruptothepracticesectionisalreadyhelpfu leven withoutanopenedIDE,butyouwillhavethegreatestpossiblelearningsuccessifyoureproduc e someofthelinesofcodeorwritesomeyourself.Intheidealcase,youhaveasystemwithadebugg

er athand,withwhichyoucanfollowFramework smodeofoperationstepbystep.Someknowledge ofGitandaGitHubaccountwouldnothurtanythingeither,butarenotessential. Found a bug? Haveyoufoundabuginthetextorcode?Pleasefeelfreetofileabugticketinthebugtracker.I amthankfulforyourfeedbackandsupport. https://github.com/michael-romer/zf2book/issues

Introduction Conventions used in this book Code examples ThelistingsinthisbookhaveSystaxHighlighting,whereverpossible,butdonotalwaysconfo rmto acodingstandard;thisservestomakethemmorelegible.PHPcodeisintroducedbya git version 1.7.0.4 Fromhereonwards,everythingisveryeasy changetothedirectoryinwhichthesubdirectoryfor theapplicationistobesetupandwhichcanlaterbemadeavailabletothewebserveras document root ,anddownloadtheZendSkeletonApplication. 1 $ git clone git://github.com/zendframework/ZendSkeletonApplication.git Admittedly,inGitjargonithastobetermed cloning andnot downloading .Butforthetime being,wewillignorethat.Andbytheway,donotbeafraidofGit!Onedoesnotneedanyadvanced GitknowledgeinordertosuccessfullyworkwiththisbookandFramework.Ofcourse,thereader canalsoadministerhisorherownapplicationcodeinthefutureevenpermanently withGit,but itisnotnecessary.Therefore,asubversion,CVSorevennosystematallcanalsobesubsequent ly usedforcodeadministrationwithoutproblems. Downloadingthe ZendSkeletonApplication isveryfast,evenforlessrapidInternetconnections , butonemustalwayshavesuchaconnectioninanycase.Thereasonforthefastdownloadisthefac

t thatFrameworkcodeitselfisnotdownloadedatall;insteadonlythecorrespondingboilerpla tecode forthedevelopmentofone sownapplication,whichisbasedonZendFramework2,isprovided. Composer The ZendSkeletonApplication useswithComposer5anotherPHTtool,whichestablisheditself forthemanagementofdependenciesforothercodelibrariessometimeago.Theideabehindthe composerisassimpleasitisingenious.Aconfigurationfilecontainsadefinitionoftheothe rcode librariesthatanapplicationisdependentonandfromwheretherespectivelibrarycanbeobta ined. Inthiscase,theapplicationisdependentonZendFramework2,ascanbeseenbylookinginthefi le composer.jsonintheapplicationroot. 4http://code.google.com/p/msysgit/ 5getcomposer.org/

Hello,ZendFramework2! 1 { 2 "name": "zendframework/skeleton-application", 3 "description": "Skeleton Application for ZF2", 4 "license": "BSD-3-Clause", 5 "keywords": [ 6 "framework", 7 "zf2" 8 ], 9 "homepage": "http://framework.zend.com/", 10 "require": { 11 "php": ">=5.3.3", 12 "zendframework/zendframework": "2.*" 13 } 14 } Listing4.16 Inlines11and12,theapplication stwodependenciesaredeclared.BothPHP5.3.3orhigherand thecurrentversionofZendFramework2arerequired.Thefollowingtwoinvocationsensuretha t ZendFramework2isdownloadedandadditionallyalsointegratedintheapplicationsuchthati tis immediatelyutilisableandthecorrespondingFrameworkClassesaremadeavailablebyautolo ading. 1 $ cd ZendSkeletonApplication 2 $ php composer.phar install

3 > Installing zendframework/zendframework (dev-master) ComposerhasnowdownloadedZendFramework2andmadeitavailablefortheapplicationinthe vendor directory. Phar-ArchiveAPharArchiveprovidestheoptionofmakingaPHPapplicationavailableinthefo rmofasinglefile.IfonelooksattheComposer-RepositoryatGitHub.,itbecomesclearthatco mposerdoesnotconsistofasinglefile,asonemightthink, butthatitscomponentsaremerelybundledinaPharArchivefordistributionoftheapplicatio n. .https://github.com/composer/composer 6https://gist.github.com/3820657

Hello,ZendFramework2! PharArchiveandSuhosinIf Suhosin .isusedonasystem,theuseofPharmustinitiallybeexplicitl ypermittedsuchthatthesuhosin.iniisextendedbytheentrysuhosin.executor.include.whi telist=phar.Otherwise,problemscanoccurintheexecutionoftheComposercommand. .http://www.hardened-php.net/suhosin/ InstallationwithoutGitorComposerIfnecessary,itisalsopossibletoobtainFrameworkand the ZendSkeletonApplication viaa normaldownload orPyrus(thesuccessortoPEAR).Additionalinstallationinform ationistobefoundontheofficialdownloadsite.. .http://framework.zend.com/downloads A first sign of life Wehavenowcompletednearlyalloftherequiredpreparations.Finally,weonlyhavetoensure thattheapplication spublic directoryisconfiguredasDocumentRootofthewebserverandcan becalledup/invokedviatheURL http://localhostbythebrowser. Forexample,toachievethis,adirectiveinfollowingexemplaryformmustbespecifiedinthe httpd.confofApache: 1 // [..] 2 DocumentRoot /var/www/ZendSkeletonApplication/public 3 // [..] whereitisrequiredthatthe ZendSkeletonApplication wasdownloadedwiththefollowing commandbeforehand: 1 $ cd /var/www 2 $ git clone git://github.com/zendframework/ZendSkeletonApplication.git

Hello,ZendFramework2! SettingupaPHPruntimeenvironment. Sincethescopeofmyreaders previousknowledgeisprobablyextremelydifferent,IwillnotexplainexactlyhowawebserverisinstalledonasystemtogetherwithPHPatthis time,butinsteadpresumethatmyreadersalreadyknowthis. Foranyonewhoneedsassistance,additionalinformationandsupportaretobefoundintheAppe ndixofthisbook Iftheseconfigurationshavebeenmade,ZendFramework2shouldshowitselfforthefirsttime whenhttp://localhost iscalledupinthebrowser:

StartpageZendSkeletonApplicationofZendFramework2 Directory structure of a Zend Framework 2 application Now,wecanfinallylookatit,aZend\Mvc-basedZendFramework2applicationwithitscharacte risticdirectorylayoutandthetypicalconfigurationandinitialisationcode: 1 ZendSkeletonApplication/ 2 config/ 3 application.config.php 4 autoload/ 5 global.php 6 local.php 7 ... 8 module/ 9 vendor/

Hello,ZendFramework2! 10 public/ 11 .htaccess 12 index.php 13 data/ Inourcasethe ApplicationRoot istheZendSkeletonApplication directory,whichisautomaticallygeneratedbycloningtheappropriateGitHubrepository. Intheconfig directory,thereis,on theonehand,application.config.php,whichcontainsthebasicconfigurationforZend\Mvc and itscollaboratorsasaPHParray. Inparticular,theModuleManager isconfiguredthere;wewill frequentlytalkaboutitsdetailsinthecourseofthebook. Ifrequired,theautoload directory containsadditionalconfigurationdataintheformofadditionalPHPfiles;initially,thiss eems abitstrange,butonebecomesaccustomedtoit.Tobeginwith,thedirectory sdesignationas autoload isabitirritating.Inthislocation, Autoload hasnothingtodowiththe Autoloading ofPHPClasses,butinsteadindicatesthattheconfigurationsthatarefiledinthisdirectory willbe automaticallytakenintoconsideration.Andthatoccurschronologicallyaftertheconfigur ationof theapplication.config.php andalsoaftertheconfigurationsperformedbytheindividualmodules, whichwewilltalkaboutlater.Thissequenceofconfigurationevaluationisextremelyimport ant becauseitallowsthesituation-dependentoverwritingofconfigurationvalues.Thesamepri nciple appliestoglobal.php undlocal.php:configurationsintheglobal.php arealwaysvalid,butthey canbeoverwrittenbyconfigurationsinthelocal.php.Technicallyspeaking,Frameworkinit ially readsintheglobal.php andsubsequentlythelocal.php,wherebypreviouslydefinedvaluescan bereplaced,ifnecessary.Whatisthatgoodfor?Inthismanner,configurationscanbedefined independentlyoftheruntimeenvironment.Letusassumethattheprogrammersofanapplicatio n havesetuparuntimeenvironmentlocallyontheircomputers.SinceaMySQLdatabaseisrequire d fortheapplication,allofthedevelopershaveinstalledthisontheircomputersandinthepro cesshave configuredtheaccessrightssuchthatpasswords,whichtherespectivedevelopersalsoother wise frequentlyuse,areutilised.Itisindeedmoreconvenient.However,sinceeachdeveloperpot entially hasanindividualpasswordforthedatabase,thisconfigurationcannotbehard-wired,butmus

t beindividuallyspecified.Toachievethis,thedeveloperentershisorherconnectiondatain the local.php file,whichheorshemaintainslocallyinthecomputeranddoesnotcheckintothe codeadministrationsystemeither.Whereastheconnectiondataforthe livesystem aredeposite d inglobal.php file,everydevelopercanworkwithhisorherownconnectiondata,whichare definedwiththeaidofthelocal.php.Inthismannerevenspecialconfigurationsfortestorst aging systemscanbedeposited.Incidentally,configurationfilesoftheform xyz.local.php (alsoap plies to global ),forexampledb.local.php,arealsoprocessedbyFrameworkasdescribedabove. TheindividualmodulesoftheapplicationarelocatedintheModule directory.Eachmodulecomes withitsowntypicaldirectorytree,whichwewilltakeacloserlookatlater.However,atthist imethe importantthingisthateverymodulecanalsohaveitsownconfiguration.Wenowhavethreeplac es inwhichsomethingcanbeconfigured:application.config.php,module-specificconfigurat ion andtheglobal.php andlocal.php files(ortheir specialisations asdescribedabove),whichthe systemreadsinexactlythisorderandultimatelyprovidealarge,commonconfigurationobjec t, becauseinthecourseofexecutionexactlytheseconfigurationsaremerged.Iftheconfigurat ions

Hello,ZendFramework2! ofapplication.config.php areonlyofinterestinthefirstfewmetersofbootstrapping,the configurationsofthemodulesandthosefromglobal.php andlocal.php arealsoimportantin thelatercourseoftheprocessingchainandaregenerouslymadeavailablebytheServiceManag er. Wewillalsolearnmoreaboutthislater.Theattentivereaderrealisesatthistimethatasares ultof this configurationcascade ,forexamplemoduleconfigurationsthatflowintotheapplicationf rom thirdpartymanufacturers modulescanbeextendedorevenreplaced.Thisisverypractical. Thevendor directorycontainsconceptionallythecodewhichonedidnotwriteoneself(ignoring the ZendSkeletonApplication codeatthistime,butwhichonecouldhavehadtowriteoneselfin caseofdoubt)orwhichonedidnotwriteespeciallyforthisapplication.ZendFramework2isth us locatedapproximatelythere,but,ifnecessary,alsoinotherlibraries.Whendealingwithad ditional libraries,onemustalwaysensurethatthecorrespondingclassescanbeaddressedbytheappli cation. However,ifonecaninstalltherespectivelibraryusingcomposer,thisworkdoesnothavetobe donebythedevelopereither.Theinstallationofadditionallibrariesshouldthereforeinth eideal casealwaysbeperformedusingcomposer.ThefactthatalsotheZF2modules,whichactually shouldbelocatedinthemodule directory,canalsobemadeavailableviathevendor directory isalsointeresting.(Tobeperfectlycorrect,onewouldhavetosaythatiscanbeconfiguredvi a application.config.php andthemodulescanthereforebasicallybedepositedanywhere.)This meansthatthirdpartymanufacturers librariesthatadheretotheZendFramework2module standardcanalsobeaddedinthismanner.Thus,onecanensurethatonlythosemodulesthat oneactuallydevelopedinthescopeoftherespectiveapplicationarelocatedinthemodule directory. Allothermodulescanalsobemadeavailableviavendor Allfilesthataretobemadeexternallyaccessibleviathewebserver(withtheexceptionofspe cific restrictionsinwebserverconfiguration)arelocatedinpublic.Thisisalsotheplaceforima gesCSS orJSfilesaswellasforthe centralentrypoint ,theindex.php.Theideabehindthisisthatevery HTTPrequestthatreachesthewebserverandaspecificapplicationinitiallyresultsincalli ngupthe index.php.Always.RegardlessofhowtheURLcallitselfisformulated.Theonlyexceptionsar e URLsthatrefertoanactuallyexistingfilewithinorbelowthepublic directory.Onlyinthiscase, doestheindex.php notperformtheexecution,insteadtheappropriatefileisreadandreturned.This

mechanismisachievedbyatypicalZendFramework.htaccess fileinthepublic directory: 1 RewriteEngine On 2 RewriteCond %{REQUEST_FILENAME} -s [OR] 3 RewriteCond %{REQUEST_FILENAME} -l [OR] 4 RewriteCond %{REQUEST_FILENAME} -d 5 RewriteRule ^.*$ -[NC,L] 6 RewriteRule ^.*$ index.php [NC,L] Inorderforthistofunction,severalconditionsmustbefulfilled.Ontheonehand,thewebser ver mustbeequippedwithaso-calledRewriteEngine7,whichmustalsobeactivated.Ontheother hand,thewebserverhastoallowanapplicationtosetdirectivesviaitsown.htaccess.Toachi eve this,the[followingdirective]mustbeexemplarilyintheApachehttpd.conf . 7http://httpd.apache.org/docs/current/mod/mod_rewrite.html

Hello,ZendFramework2! 1 AllowOverride All Thedata directoryisrelativelyunspecific.Basically,dataofallkinds,whichhaveanythingto dowiththeapplication(documentation,testdata,etc.)orthataregeneratedintherunningt ime (cachingdata,generatedfiles,etc.),canbedepositedthere. The index.php file Everyrequestthatdoesnotmapontoafilethatactuallyexistsinthepublic directoryisthus redirectedviathe.htaccess filetotheindex.php.Itthereforehasaspecialimportanceforwork withZendFramework2.Atthistime,itisagainimportanttorealizethattheindex.php itselfis notpartofFramework,butthatitisindispensibleforusingtheFramework sMVCcomponents. Pleaseremember:Zend\Mvc isthecomponentthatrepresentsthe processingframework foran application.Theindex.php comeswiththeZendSkeletonApplication;thus,wedonothaveto developitourselves. Becauseoftheimportanceoftheindex.php bothforFrameworkandforourunderstandingof Framework smechanics wewillnowriskadetailedlookatthisveryeasilyunderstoodfile: 1 4 5 // [..] Listing10.4 Layouts Ifoneknowshowtonest viewmodels ,onecanquicklydeducethemodeofoperationoflayouts. Butperhapsweshouldfirsttakeastepbackwards:TheideabehindlayoutsistoacquireHTML code,whichisrequiredbymanyorevenallcontrollersandactions(forthepresentwe llreducei t tothisforsimplicity ssake;but,ofcourse,datastructuresbeyondHTMLcanalsobegeneratedw ith ZendFramework2).TheseincludeMETAtags,thebasicHTMLframework,referencestoCSSfiles andthelike. Inatechnicalsense,alayoutisreallynothingmorethanaViewModel thatreferencesaViewModel, whichwasgeneratedbyacontrolleraction,as child justasintheexamplegivenabovethe ViewModel ofacontrolleractionreferencedthatofanothercontrolleraction.Toaccessthecontroller action sViewModel withinthelayouttemplate,Frameworkautomaticallyregistersthecontent key ;justaswemanuallygeneratedthewidgetContent keyinthepreviousexample.Thus,inthelayout templatetheresultofacontrolleractioncanbeaccessedinthefollowingmanner: 1 2 3 Meine Seite 4

5 6 7 8 Listing10.5 ThelayouttemplatethatisautomaticallyconsultedbyFrameworkcanbecontrolledviathe controllerplugin,whichwasdiscussedinthepreviouschapter,orinsteadviaa viewhelper ,whi ch wewillalsoexamineinmoredetailinthefollowing. View Helper ItisfrequentlynecessarytofurtherprocesstheViewModel s datainthecourseofrenderingorto generateadditionaldata.Thus,forexample,inthecontextofsubjectssuchas navigation , META

Views 103 tags ,etc.therearemanyrecurrentview-relatedtaskswhichonecanmasteronceandthenmake re-usableintheformof viewhelpers .Asstandard,ZendFramework2providesalargenumber ofready-to-useviewhelpers,whichonecanimmediatelyuse.Inaddition,onecanwriteone sown viewhelpers. Writing a view helper of one s own InZendFramework2,aviewhelperisreallynothingspecial;itisjustamoreorless normalclass , whichactuallyonlyexpectsa getter anda setter andwhichisinjectedviatheviewinwhich therespective viewhelper isnowbeingapplied.However,onecanavoidimplementingthese methodswhenonederivesone sownviewhelpersfromtheZend\View\Helper\AbstractHelper class.Thenonemustmerelyfillthe__invoke() methodwithlifeinordertobeabletoeasilyuse theviewhelper. 1 2 $this->displayCurrentDate(); ?> Listing10.7 DisplayCurrentDate canbeveryeasilyinvokedasifitwereamethodofthecurrentview(via $this). However,inorderforthisinvocationtofunction,wemustmakeDisplayCurrentDate knowntotheViewHelperManager beforehand.Wecandothiseitherindermodule.config.php ofthemoduleorinitsModule class:

Views 104 1 Produkt hinzugefgt! 2 Produkt hinzugefgt! 3 4 5 6 7 Produkt konnte nicht hinzugefgt werden. 8 9 10 11