Table Of ContentWeb Development with Zend Framework 2
Concepts, Techniques and Practical Solutions
Michael Romer
Thisbookisforsaleathttp://leanpub.com/zendframework2-en
Thisversionwaspublishedon2013-03-10
ThisisaLeanpubbook. LeanpubempowersauthorsandpublisherswiththeLeanPublishing
process. LeanPublishingistheactofpublishinganin-progressebookusinglightweighttoolsand
manyiterationstogetreaderfeedback,pivotuntilyouhavetherightbookandbuildtractiononce
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.
“Early access” means that you can already begin reading the book while the subsequent chapters
are still being written. They will be made available to you as soon as they are finished. Thanks
to the lean publishing concept¹, you are also now much more up to date than you have ever been
before. The contents of this book refer to Version 2.0 of Framework, they will very probably also
unconditionally valid to later versions. It is very possible that you might find a number of spelling
errors or also a bug or two in the code examples in the early access edition. At the present time no
one has supported me with proofreading or editing in order to reduce the number of errors in this
booktoaminimum. Naturally,Iattempttobeworkascarefullyaspossible,butIcannotguarantee
absolutefreedomfromerrorsatthistime. Pleasebearwithme. Ifyouwouldliketohelpmeimprove
thisbook,feelfreetoparticipateinthebook’sonlinecommunityandletmeknowaboutyourideas
oranyissuesyoudiscoverwithininthebook. Iwouldgreatlyappreciateit.
The book’s online community
Foundabugwithinthebook? WanttotalkaboutthebookcontentsorZendFramework2ingeneral?
Please feel free to join the book’s online community, the Google-Group “Web Development with
ZendFramework2Book”². YouwillneedaGoogleAccountwhichmaybesetupfreeofcharge.
Important notice for Amazon customers
If you bought this book at Amazon, it is currently somewhat more difficult to ensure that you
automaticallyreceiveallofitsupdatesastheyarepublished. Toavoidproblems,pleasesendashort
email with “Updates ZF2 book” in the subject line to [email protected]. In this manner,
you can be certain that you will really always have the latest version of the book. As thanks for
youreffortsyouwillalsoadditionallyreceivethePDFandEPUBversionsofthebook.
¹http://leanpub.com/
²https://groups.google.com/forum/#!forum/web-development-with-zend-framework-2-book
1
Introduction
Zend Framework 2 is an open source Framework for the development of professional web applica-
tions for PHP Version 5.3. and higher. It is operated on the server and is primarily used to produce
dynamic web contents or conduct transactions such as purchasing a product in an online shop.
In this context, Zend Framework 2 can support the development of any type of (web )application
because it provides universally applicable solutions that can be used in e commerce, content,
communityorSaaSapplicationsequallywell. ZendFrameworkisessentiallybeingdevelopedbythe
Zend Company, which also gave Framework its name and provides it with a sold (financial) basis,
not least also because Zend itself is also involved in the development of the PHP programming
language. However, in addition to Zend, a number of prestigious companies also support Zend
Framework and are interested in its long-term success. Among them are also Microsoft and IBM.
AlloftheaboveprovidessecurityfortheselectionofZendFrameworkandalsomakesitsselection
agooddecisionasthebasisforone’sownapplicationfromaneconomicpointofview.
Zend Framework in the stable Version 1.0 first appeared on the scene on 30/06/2007 and has since
made a lasting impression on the face of web development with PHP One can truly say that
programmingwithPHPalsofirstbecamereallyacceptableforapplicationscriticaltocompanywith
Zend Framework. If one previously put one’s trust in complex J2E (Java) applications in corporate
contexts, in the meantime PHP and Zend Framework are gladly chosen with a clear conscience
because this combination indeed provides a balanced ratio of lightness and professionalism that
practicallynootherplatformcanachieve.
IfonetakesthefirstpreviewreleasesofZendFramework1intoconsideration,todayFrameworkis
already more than 6 years old. Even if much has been achieved in the innumerable releases from
the first preview up to the current version 1.11, a number of urgently needed improvements and
extensionscouldnolongerbeimplementedontheoldcodebase;thisjustifiesanewmajorrelease,
whichisforthefirsttimenolongercompatibletoearlierversions. Itistimeforanewbeginning.
Zend Framework 2 marks the next milestone in the evolution of the PHP web frameworks, but
also of PHP itself, for as one has recently seen on the examples of Java and Ruby, a good
programming language alone is not enough to also be really successful on a broader front. Only
with frameworks—such as Struts, Spring, Rails or indeed also Zend Framework—that are based on
the programming language and also significantly reduce the initial development effort but also,
long-term maintenance effort of an application, does a web development platform really become
established.
For whom is this book?
It is a challenge to write a technical book which finds a balance between theory and practice and
allowsbothnovicesandprofessionalstogetthebestoutofthebook. Igladlyacceptedthistask,but
I left myself an escape hatch. If I have the feeling that we are getting lost in a forest of details that
2
Introduction 3
cannot be explained in greater detail at the respective location or even entirely in this book, I refer
thereadertopassageslateroninthebookortosecondaryliteraturesources.
AfurtherchallengeiswhetherornotmyreadershaveanypreviousknowledgeofZendFramework.
AdeveloperwhohasonlyjustbeguntoworkwithVersion2ofZendFrameworkrequiresdifferent
information in some places than an “old hand”, quickly finds his or her way around the many
corners in Version 2 because he or she is already familiar with ideas and concepts from Version 1.
ForallthosewhoarefamiliarwithVersion1,IwillfrequentlyrefertothepredecessorofVersion2
at appropriate places—whenever I consider it necessary—without going into excessive detail. That
might also perhaps help novices, because in this manner they would get a better feeling for why
Version2isnecessary. ThisbookshouldbehelpfulforbothnovicesandadvancedlearnersofZend
Framework.
IpresumethatyouhavebasicknowledgeofPHP.YoudonothavetobeaPHPexpert,particularly
because many “native” PHP functions even became obsolete when one used Framework, for
example, Session Management, which maps in an object-oriented manner and in this manner
thankfully abstracts some of the low-level functionality. Hence, if you are accustomed to PHP
syntax,haveabasicunderstandingoftheoperatingprinciplesofPHPapplicationsandarefamiliar
withthecommon functionsof thelanguagecore,youarewellprepared. If necessary,youwill also
havetouseaPHPhandbook.
You & I
Hi,IamMichael. Ihopethatyouwon’tobjectifIoccasionallyusecontractionsandthelessformal
“you”insteadof“one”inmyexplanations. Thatmakeswritingiteasierformmeandensuresaless
formalatmosphere.
Structure of this book
This book is not meant to be a compendium, but rather a pragmatic and practice-oriented
introduction to the basic concepts and practical work with Zend Framework 2. From a certain
point in one’s progress as a developer onward, the official documentation serves as a compendium
for experienced developers, but it is not really appropriatefor use while youarebecoming familiar
withthesubject;instead,itservesasan(indispensible)referenceworkforfurtherdetailedquestions
after one has achieved the required basic understanding of the program. And exactly that is this
book’sobjective.
Itisstructuredsuchthatyoucanreaditfromthebeginningtotheend,andthatiswhatyoushould
do. We will begin with an overview of Framework and will first look at the essential concepts and
ideas which make up the essence of Framework and also differentiate it from its predecessors. On
the way, we will repeatedly also look to the left and to the right and thus become familiar with
some framework conditions, for example how Framework was really developed. Then we will go
Introduction 4
into more detail and elucidate Framework’s most important components and relationships; then
take a look at how a HTTP request is processed and write our first bit of code. This is followed
by an excursion into the Framework environment. We will examine the most important modules,
which have been made available by third parties and, for example, make the realisation of a user
administrationofone’sownobsolete. AlargepartofthemagicofthenewFrameworkversionisthe
resultofthemoduleconcept,andmodulescan—aswewillseelater—greatlyaccelerateandsimplify
the development of your own applications. It is to be expected that in a short time a large number
ofhigh-qualitymoduleswillbeavailableforZendFramework2.
Last but not least, there is an additional, intensive practice section in the form of a “developer’s
diary”. We will develop a web application together, which is also intended to really be used
subsequentlybyabusinessenterprise;forthisreasonitisbetterifwereallytryhard. Atthelatest,
wewillbegindoingreal“hands-on”workatthispoint.
Repetitions
You will soon realise that I frequently explain contexts several times in this book This can be due
to two things: 1) that I lost track of what I had already said and what I had not (:-D) or 2) that
I consciously intended to do it. For even the old Romans knew that: Repetitio mater studiorum
est – Repetition is the mother of learning. But also the fact that the respective contexts are in
a different context in each case and thus discussed from another perspective is also conducive to
comprehension. Thus, if you happen to find a place in the book where you think, “I already know
allthat!”,justbegladthatyouhavelearnedsomuchandcontinuereadingorjustskiptherespective
passage.
How you can best work with this book
Programming (or handling a programming framework) is best learned when you become active
yourself. Indeed, particularly the first chapter up to the practice section is already helpful even
without an opened IDE, but you will have the greatest possible learning success if you reproduce
someofthelinesofcodeorwritesomeyourself. Intheidealcase,youhaveasystemwithadebugger
athand,withwhichyoucanfollowFramework’smodeofoperationstepbystep. Someknowledge
ofGitandaGitHubaccountwouldnothurtanythingeither,butarenotessential.
Found a bug?
Have you found a bug in the text or code? Please feel free to file a bug ticket in thebug tracker³. I
amthankfulforyourfeedbackandsupport.
³https://github.com/michael-romer/zf2book/issues