Zend Framework 2 Cookbook
()
About this ebook
Related to Zend Framework 2 Cookbook
Related ebooks
Zend Framework 2 Cookbook: If you are pretty handy with PHP, this book is the perfect way to access and understand the features of Zend Framework 2. You can dip into the recipes as you wish and learn at your own pace. Rating: 0 out of 5 stars0 ratingsMeteor: Full-Stack Web Application Development Rating: 0 out of 5 stars0 ratingsDjango: Web Development with Python Rating: 0 out of 5 stars0 ratingsOracle JDeveloper 11gR2 Cookbook Rating: 0 out of 5 stars0 ratingsSpring MVC Cookbook Rating: 0 out of 5 stars0 ratingsAngular 2 Cookbook Rating: 0 out of 5 stars0 ratingsIBM DB2 9.7 Advanced Application Developer Cookbook Rating: 0 out of 5 stars0 ratingsFlash iOS Apps Cookbook Rating: 0 out of 5 stars0 ratingsEntity Framework Core Cookbook - Second Edition Rating: 0 out of 5 stars0 ratingsVMware vRealize Orchestrator Cookbook Rating: 0 out of 5 stars0 ratingsMEAN Web Development - Second Edition Rating: 0 out of 5 stars0 ratingsNode Cookbook Rating: 0 out of 5 stars0 ratingsServiceStack 4 Cookbook Rating: 0 out of 5 stars0 ratingsOdoo Development Cookbook Rating: 0 out of 5 stars0 ratingsASP.NET jQuery Cookbook - Second Edition Rating: 0 out of 5 stars0 ratingsD Cookbook Rating: 0 out of 5 stars0 ratingsMeteor Cookbook Rating: 5 out of 5 stars5/5TYPO3 4.3 Multimedia Cookbook Rating: 0 out of 5 stars0 ratingsMicrosoft SQL Server 2012 Integration Services: An Expert Cookbook Rating: 5 out of 5 stars5/5Microsoft System Center 2012 Configuration Manager: Administration Cookbook Rating: 0 out of 5 stars0 ratingsSilverStripe 2.4 Module Extension, Themes, and Widgets: Beginner's Guide Rating: 0 out of 5 stars0 ratingsBusiness Intelligence with MicroStrategy Cookbook Rating: 0 out of 5 stars0 ratingsSpring Roo 1.1 Cookbook Rating: 0 out of 5 stars0 ratingsPHP 7: Real World Application Development Rating: 0 out of 5 stars0 ratingsVisual Studio 2013 Cookbook Rating: 0 out of 5 stars0 ratingsManaging Data and Media in Silverlight 4: A mashup of chapters from Packt's bestselling Silverlight books Rating: 0 out of 5 stars0 ratingsDotNetNuke 5.4 Cookbook Rating: 5 out of 5 stars5/5Learning DevOps: Continuously Deliver Better Software Rating: 0 out of 5 stars0 ratings
Programming For You
Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsPython Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5Raspberry Pi Electronics Projects for the Evil Genius Rating: 3 out of 5 stars3/5Problem Solving in C and Python: Programming Exercises and Solutions, Part 1 Rating: 5 out of 5 stars5/5C Programming For Beginners: The Simple Guide to Learning C Programming Language Fast! Rating: 5 out of 5 stars5/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5HTML in 30 Pages Rating: 5 out of 5 stars5/5Learn JavaScript in 24 Hours Rating: 3 out of 5 stars3/5Microsoft Azure For Dummies Rating: 0 out of 5 stars0 ratingsSpies, Lies, and Algorithms: The History and Future of American Intelligence Rating: 4 out of 5 stars4/5Nostalgia and Videogame Music: A Primer of Case Studies, Theories, and Analyses for the Player-Academic Rating: 0 out of 5 stars0 ratingsCoding with JavaScript For Dummies Rating: 0 out of 5 stars0 ratings
Reviews for Zend Framework 2 Cookbook
0 ratings0 reviews
Book preview
Zend Framework 2 Cookbook - Josephus Callaars
Table of Contents
Zend Framework 2 Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers and more
Why Subscribe?
Free Access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Zend Framework 2 Basics
Introduction
Setting up a Zend Framework 2 project
Getting ready
How to do it…
Cloning the skeleton
Moving the skeleton
Initializing the Composer
How it works…
There's more…
See also
Handling routines
How to do it…
Setting up routing
Using SimpleRouteStack
Using TreeRouteStack
How it works…
There's more…
Namespace – Zend\Mvc\Router\Http
The Hostname class explained
The Literal class explained
Methods explained
The Part class explained
Regex explained
The Scheme class explained
The Segment class explained
Understanding dependency injection
How to do it…
Initializing the DI at call-time
Initializing the DI through a Configuration object
How it works…
The DI only gives out one instance of an object
Defining either all properties, or using a Fully Qualified (FQ) setter parameter
There's more…
Using configurations to your benefit
How to do it…
Creating a global configuration
Creating configuration that only works for a local machine
Editing your application.config.php file
How it works…
There's more…
The EventManager and Bootstrap classes
How to do it…
Using the bootstrap
Starting a session
Using the EventManager class
Changing the View output
How it works…
The Observer pattern explained
Aspect-Oriented Programming (AOP) explained
Event-driven architecture explained
There's more…
2. Translating and Mail Handling
Introduction
Translating your application
Getting ready
How to do it…
Setting up and checking the essentials
Translating strings in the controller
Translating strings in the View
Translating strings with Poedit
How it works…
Basic set up of translation in your module
There's more…
PHP array
Gettext
Ini
Localizing your application
How to do it…
So it begins
Localizing currencies
Localizing date/times
How it works…
Identifying the client language
Localizing currencies and dates
Sending mail
How to do it…
Transport\Sendmail
Transport\Smtp
Transport\File
How it works…
Sending mail through SMTP
Sending mail through files
Receiving mail
Getting ready
How to do it…
Connecting to an IMAP mail server
Connecting to a POP3 mail server
Working with flags on IMAP or Maildir connections
Maildir++ Quota system
Keeping a connection alive
How it works…
Connecting to a POP3 server
About the Maildir++ Quota system
Keeping the connection alive
There's more…
3. Handling and Decorating Forms
Introduction
Creating forms
Getting ready…
How to do it…
Creating a basic form
Defining a form that is extended from Zend\Form
Defining a form that uses the Zend\Form\Annotation
Adding elements to a Zend\Form extend form
Adding elements to an annotated form
Validating form input
How it works…
Setting up a basic form
Setting up an annotated form
Adding elements to the form
Forms, filtering, and validation
There's more…
Using form view helpers
How to do it…
Form
FormButton
FormCaptcha
FormCheckbox
FormCollection
FormColor
FormDate, FormDateTime, and FormDateTimeLocal
FormEmail
FormFile
FormHidden
FormImage
FormInput
FormLabel
FormElementErrors
How it works…
Form
FormButton
FormCaptcha
FormCheckbox
FormCollection
FormColor
FormDate, FormDateTime, and FormDateTimeLocal
FormEmail
FormFile
FormHidden
FormImage
FormInput
FormLabel
FormElementErrors
Creating a custom form element and form view helper
How to do it…
Creating the new element
Creating the new view helper
Adding view helper to the configuration
Displaying the new element
How it works…
Creating the element
What did we do
4. Using View
Introduction
Working with View
Getting ready
How to do it…
Configure the ViewManager
Set variables in the ViewModel instance
Mark up the template file
How it works…
The configuration
The ViewModel instance
The ViewStrategy class
The ViewRenderer helper
Getting ready
How to do it…
The BasePath view helper
The Doctype view helper
The URL view helper
The Partial view helper
How it works…
Zend\View\Helper\AbstractHelper
The BasePath view helper explained
The Doctype view helper explained
The URL view helper explained
The Partial view helper explained
There's more…
Creating a global layout template
Getting ready
How to do it…
Creating the main layout file
Creating the error templates
How it works…
Creating reusable Views
Getting ready
How to do it…
Use the Action view helper to get the re-usable content
Define a child to the ViewModel instance
How it works…
The Action view helper explained
Defining a child to a ViewModel instance explained
Pros and cons
Using view strategies/renderers
Getting ready
How to do it…
Adding a view strategy
The JSON strategy
The Feed strategy
How it works…
The view strategy class
The default view strategies
The JSON strategy explained
The Feed strategy explained
More about view strategies
Using context switching for a different output
Getting ready
How to do it…
Define multiple strategies to output
Determine the view model based on the Accept header
How it works…
There's more…
Writing a custom view strategy/renderer
How to do it…
Creating the XmlOutput renderer
How it works…
The XmlRenderer and XmlModel
The XmlStrategy
There's more…
5. Configuring and Using Databases
Introduction
Default database engines available
IBM DB2 driver
MySQLi driver
OCI8 driver
PGSQL driver
SQLSRV driver
PDO driver
Connecting to a database
Getting ready
How to do it…
Connecting to a MySQL database through the configuration
Connecting to multiple databases through the configuration
Connecting to a MySQL database through code
How it works…
Connecting to a MySQL database through the configuration
Connecting to multiple databases through the configuration
About the ServiceManager
Executing simple queries
Getting ready
How to do it…
Using raw SQL
Using the prepared statements
Quote identifier
Quote identifier chain
Quote (trusted) value
Quote value list
Quote identifier in fragment
How it works…
Using raw SQL
Using prepared statements
Quoting in our SQL
Using createStatement
Executing queries using TableGateway
Getting ready
How to do it…
Inserting a new record
Updating a record
Deleting a record
Advanced selects – joins conditions
How it works…
Optimizating with a DB profiler
Getting ready
How to do it…
Setting up a new profiler
How it works…
There's more…
Creating a Database Access Object
Getting ready
How to do it…
Creating our new module and configuration
Creating a connector
Creating a mapper interface
Creating an abstract mapper class
Creating a Data Transfer Object
Creating a mapper class
How it works…
About the DAO
About the recipe
6. Modules, Models, and Services
Introduction
Creating a new module
Getting ready
How to do it…
Creating the Module.php
Attaching to the loadModules.postevent
Implementing the getAutoloaderConfig
Implementing the getControllerConfig, getControllerPluginConfig and getViewHelperConfig
How it works…
Creating a new module directory
Creating the Module.php
Optionally act on ModuleManager events
Understanding the loadModules event
The loadModules.resolve event
The loadModule event
The loadModules.post
Attaching to the loadModules.post event
More specific non configuration file Module configuration
The getAutoloaderConfig method
The getControllerConfig, getControllerPluginConfig, and getViewHelperConfig methods
Using modules as a widget
Getting ready
How to do it…
Creating the Comment/Controller/Index
Using a view helper to display the comments statically
Using the forward to render the comments statically
Getting the comments through AJAX
How it works…
Using a view helper to display the comments statically
Using the forward() method to render the comments statically
Getting the comments through AJAX
About Widgetizing
A Model and a Hydrator
Getting ready
How to do it…
Accessing the Model
Creating a Hydrator
Creating a Hydrator strategy
How it works…
Think about the model's purpose
Think about the model's location
Think about the model's methods
Unit test the model
Document your class
Creating a hydrator
Creating a hydrator strategy
About models
There's more…
A basic service
Getting ready
How to do it…
Creating a service
Getting a service from within a controller
How it works…
7. Handling Authentication
Introduction
Understanding Authentication methods
Getting ready
How to do it…
The DbTable adapter
The Http adapter
How it works…
The DbTable adapter (again)
The Http adapter (again)
The Digest adapter
The LDAP adapter
About Authentication
Setting up a simple database Authentication
Getting ready
How to do it…
Setting up the module initialization
Creating the authentication service
Setting up the controller and action
How it works…
Writing a custom Authentication method
Getting ready
How to do it…
Creating our adapter
The adapter outline
Creating a getter and setter for any error messages
Making sure we have a secure connection
Checking if the certificate is an actual certificate
Checking if we have all the certificate fields
Checking if the certificate isn't expired yet
Creating a getter and setter for the Database adapter
Creating the authenticate method
How it works…
What are we trying to achieve
About certificates
There's more…
8. Optimizing Performance
Introduction
Caching and when to Cache
Getting ready
How to do it…
Caching configuration
Caching output
Caching the class map
How it works…
Understanding and using storage plugins
How to do it…
Using the ClearExpiredByFactor plugin
Using the ExceptionHandler plugin
Using the IgnoreUserAbort plugin
Using the OptimizeByFactor plugin
Using the Serializer plugin
Using any plugin
How it works…
Setting up a caching system
Getting ready
How to do it…
Benchmarking our application before cache
Implementing configuration/class map cache
Implementing the class caching
How it works…
9. Catching Bugs
Introduction
Handling Exceptions – your partner in crime
Getting ready
How to do it...
Exception classes in Zend Framework 2
Handling Exceptions on dispatch or rendering
How it works...
Exception classes in Zend Framework 2
Handling exceptions on dispatch or rendering
About try-catch
See also
Logging and how it makes your life easier
Getting ready
How to do it...
Implementing a really simple file logger
Implementing a FirePHP logger
How it works...
Implementing a really simple file logger
Implementing a FirePHP logger
About the Logger
Unit testing – why would you do it
Getting ready
How to do it...
Pseudo-code examples
How it works...
What is unit testing
When should we test? – before, or after code is written
It is a matter of discipline
Setting up and using unit testing
Getting ready
How to do it...
Setting up the test framework
How it works...
There's more...
See also
A. Setting up the Essentials
Making sure you have all that you need
Installing Zend Server Community Edition on a Linux environment
Installing Zend Server Community Edition on a Windows environment
First-time run of Zend Server
See also
Downloading Zend Framework 2 and finding its documentation
Finding Zend Framework 2
Coding in the phpcloud
The documentation and getting started guide
See also
Composer and its uses within Zend Framework 2
The composer.json file
Upgrading packages
See also
Basic Zend Framework 2 structures
Folder – config
Folder – module
Folder – public
Folder – vendor
File – init_autoloader.php
What's next?
About storage adapters and patterns
Storage adapter's implementations
Storage adapters
Apc caching
Dba caching
File system caching
Memcached caching
Memory caching
Redis caching
Session caching
WinCache caching
XCache caching
ZendServerDisk caching
ZendServerShm caching
Cache patterns
The CallbackCache pattern
The CaptureCache pattern
The ClassCache pattern
The ObjectCache pattern
The OutputCache pattern
The PatternOptions pattern
Explaining the difference
Index
Zend Framework 2 Cookbook
Zend Framework 2 Cookbook
Copyright © 2013 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: December 2013
Production Reference: 1121213
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-84969-484-1
www.packtpub.com
Cover Image by Prashant Timappa Shetty (<sparkling.spectrum.123@gmail.com>)
Credits
Author
Josephus Callaars
Reviewers
Armando Padilla
Diego Sapriza
David Weinraub
Acquisition Editor
Joanne Fitzpatrick
Lead Technical Editor
Balaji Naidu
Technical Editors
Pratik More
Pooja Nair
Anita Nayak
Project Coordinator
Abhijit Suvarna
Proofreaders
Bridget Braund
Lesley Harrison
Indexer
Hemangini Bari
Graphics
Disha Haria
Yuvraj Mannari
Production Coordinator
Adonia Jones
Cover Work
Aditi Gajjar
Adonia Jones
About the Author
Josephus Callaars is a software developer whose passion began like so many other developers at the appropriate age of twelve. Being intrigued by mathematics and software languages such as Assembler and Java, he quickly found out that his career was to be found in the abstract side. Since 2003 he has been developing software applications commercially, and always tried to stay up-to-date with the latest technologies.
Josephus has been passionate about developing ever since, and always thought it could be done better every time. He is a Zend Certified Engineer and is regularly to be found in the open source community, where he is always on the lookout for new things to learn.
I would like to thank my wife for supporting me in everything and deciding to not kick me out of the house just yet. I would also like to thank my parents for always believing in me, and teaching me the value of hard work.
About the Reviewers
Armando Padilla has over 10 years of experience in the PHP ecosystem, working with some of the best at Yahoo where he assisted with Shine, World Cup, and Winter Olympics, also as a scalability expert, he helped the RiotGames' web-scalability team by supporting the demands of its web-based gaming community. He has written two PHP books, Beginning Zend Framework and Pro PHP Application Performance, and now spends his time as the Sr. Engineering Manager at Disney Interactive.
I would like to thank Alba Luz Guevara and my baby Amanda Luz Padilla for giving me the time to tech review this book.
Diego Sapriza is a Senior Software Engineer at CASE who loves technology and applying it to solve business-related problems. Diego lives in Uruguay where he oversees the CASE web development team as well as setting the direction and strategy for how the company delivers software development solutions.
He specializes in web technologies such as PHP, MySQL, Sphinx, JavaScript, jQuery, Python, and many more. He is also an expert in Linux Server Administration. Pulling from his experiences as a manager, CTO, developer, and consultant in the IT industry, Diego maintains his vast knowledge of web technologies through extensive research and development of the latest advancements in the field. As a result he ensures that custom applications designed for clients are focused on effective solutions and improving the built environment.
A self-proclaimed libre software evangelist, Diego spends his time near the beautiful beaches of Uruguay taking pictures and spending time with his family.
David Weinraub is a Zend Certified Engineer (ZCE) specializing in application development on the LAMP (Linux, Apache, MySQL, PHP) stack. He is passionate about clean code, structured architecture, SOLID object-oriented principles, and DRY. He has experience with Zend Framework, Slim, Lithium, MongoDB, PHPUnit, Vagrant, and a range of associated technologies.
David earned his Ph.D. in Mathematics from the State University of New York, Albany, for his work on Hopf algebras. He lives in Phuket, Thailand with his wife and two wonderful children.
Also, he's a sucker for astronomy/cosmology.
www.PacktPub.com
Support files, eBooks, discount offers and more
You might want to visit www.PacktPub.com for support files and downloads related to your book.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
http://PacktLib.PacktPub.com
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.
Why Subscribe?
Fully searchable across every book published by Packt
Copy and paste, print and bookmark content
On demand and accessible via web browser
Free Access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.
Preface
A couple of years ago I was introduced to Zend Framework 1 by a friend of mine, and since then I have been a fan. Although the first framework was a real bulky framework with not much documentation, I feel that the second version of the framework improved greatly. The incredible toolshed full of features, makes this framework (personally) one of the best frameworks to work in.
But as we all probably know, because of its incredibly vast library of features the learning curve can appear very steep. That is why I felt the need to write about all the important parts of the framework, in bite-size pieces that don't overwhelm someone (you in this case) who wants to learn it.
What this book covers
Chapter 1, Zend Framework 2 Basics, talks about how we can set up a small application and run it. The dependency injection and configuration are also handled.
Chapter 2, Translating and Mail Handling, explains the importance of internationalization and localization, and the overall handling of sending and receiving of mails in our applications.
Chapter 3, Handling and Decorating Forms, demonstrates how forms are created. After that it talks about filtering, validation, and decoration of forms.
Chapter 4, Using View, covers one of the most important parts of the framework that will be discussed here, setting and rendering of the View.
Chapter 5, Configuring and Using Databases, gives out the configuration and explanation of databases that will give us an insight into how we can fully utilize them in our application.
Chapter 6, Modules, Models, and Services, mainly discusses how modules are built up, models can be hydrated, and services are defined.
Chapter 7, Handling Authentication, delves into the different ways of authenticating users and how we can create our own authentication method.
Chapter 8, Optimizing Performance, discusses the use of caching and the methods available to cache output, opcode, and how to use plugins.
Chapter 9, Catching Bugs, teaches us how to debug applications, handle exceptions, and log stuff.
Appendix, Setting up the Essentials, shows where we can find the documentation, how to set up a development environment, and shows how the composer works.
What you need for this book
To follow the book in the best possible way I would recommend using a Linux-based web server, as most of the recipes are more Linux oriented than Windows. If you are a Windows user you'll probably be better off installing a virtual machine with Linux on it, or installing a Zend Server community edition to make sure your machine is compatible for Zend Framework 2 development (you can also do this without Zend Server, but it is just more convenient).
Who this book is for
Zend Framework 2 Cookbook is for PHP developers who are fairly advanced in PHP programming. It will also be useful for developers who have a keen interest in expanding their knowledge outside the boundaries of simply scripting pages together. As unit testing and MVC will be discussed, it is beneficial for the reader to know what these technologies are, although experience with developing applications is not necessarily essential.
Conventions
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: We can either get the flags from a message by using the getFlags() method, or by using the hasFlag() method.
A block of code is set as follows:
echo $this->dateFormat(
// Format the current UNIX timestamp.
time(),
// Our date is to be a LONG date format.
IntlDateFormatter::LONG,
// We want to omit the time, defining this is
// optional as the default is NONE.
IntlDateFormatter::NONE
);
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
SampleModule/
config/
module.config.php
language/
src/
SampleModule/
Controller/
IndexController.php
view/
samplemodule/
index/
index.phtml
Module.php
Any command-line input or output is written as follows:
php composer.phar update
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: After we have done all that we can, click on OK and you can choose a location to save our file.
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to <feedback@packtpub.com>, and mention the book title via the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <copyright@packtpub.com> with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
Questions
You can contact us at <questions@packtpub.com> if you are having a problem with any aspect of the book, and we will do our best to address it.
Chapter 1. Zend Framework 2 Basics
In this chapter we will cover:
Setting up a Zend Framework 2 project
Handling routines
Understanding dependency injection
Using configurations to your benefit
The EventManager and Bootstrap classes
Introduction
In this chapter we will go through a basic Zend Framework 2 application, from download, to setup, to running it. If you are unfamiliar with how Zend Framework 2 works, and the best way to install it, you can use this chapter as a reference. Further on in the chapter, we will get somewhat deeper in the framework by looking at the dependency injection (DI) and how it can help us code more efficiently. Lastly we will go more into the details of the configuration options, the EventManager and ModuleManager.
Setting up a Zend Framework 2 project
Nothing is more exciting than setting up a new project in our favourite framework. Every time we start a new project we begin with a clean slate.
Getting ready
Before you can set up a new Zend Framework 2 application you need to make sure you have the following items ready:
A web server such as Apache running PHP Version 5.3.3 or higher that you can reach from a web browser
Git
If you don't have everything ready as mentioned, you are best off reading the topics mentioned in the See also section of this recipe (every topic we explain in this chapter is called a recipe) before you continue reading here.
We are assuming that Zend Framework 2 will be used on a Linux-based platform running an Apache 2 web server; this means that commands might not directly work on a Windows platform. Windows users, however, can set up a virtual machine with Linux on it to make full use of the book.
To install a virtual machine on Windows, we can use an application called Oracle VM VirtualBox, which is freely available. We can go to www.virtualbox.org and download plus install the latest version of VirtualBox, we can go to VirtualBoxes (http://virtualboxes.org/images/ubuntu) and download a preconfigured virtual machine from there.
All we have to do on the VirtualBoxes website is click on the latest Ubuntu (which is a distribution of Linux) link in the list, please take note of the username and password displayed there as we will need it later to login. Once the image is downloaded, it can be made ready by following the instructions in the documentation that can be found on the VirtualBoxes site (http://virtualboxes.org/doc/register-and-load-a-downloaded-image).
Assuming the image is imported we can easily start up the virtual machine and put in our username and password that has been supplied with the downloaded virtual