0% found this document useful (0 votes)
279 views24 pages

Zendframework 3 Sample

Zend Framework 3 allows you to write your applications in two fundamentally different ways, using two different architectural styles. In addition, you might not want to use Zend Framework 3 as you app foundation at all, but only use specific Framework components. First, there is the „classic MVC“ style. If you used earlier version of Zend Framework before, especially version 2, things will look familiar to you. If you are new to Zend Framework or not used to other full stack MVC PHP frameworks like Laravel yet: MVC simply means dividing your app into three interconnected parts, so as to separate internal representations of information (M =model) from the ways that information is presented (V = view) to or accepted from the user (C =controller).

Uploaded by

Anton
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
279 views24 pages

Zendframework 3 Sample

Zend Framework 3 allows you to write your applications in two fundamentally different ways, using two different architectural styles. In addition, you might not want to use Zend Framework 3 as you app foundation at all, but only use specific Framework components. First, there is the „classic MVC“ style. If you used earlier version of Zend Framework before, especially version 2, things will look familiar to you. If you are new to Zend Framework or not used to other full stack MVC PHP frameworks like Laravel yet: MVC simply means dividing your app into three interconnected parts, so as to separate internal representations of information (M =model) from the ways that information is presented (V = view) to or accepted from the user (C =controller).

Uploaded by

Anton
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Web Development with Zend Framework 3

Michael Romer
This book is for sale at http://leanpub.com/zendframework
This version was published on 2016-07-07

This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing
process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and
many iterations to get reader feedback, pivot until you have the right book and build traction once
you do.
2016 Michael Romer

Also By Michael Romer


Webentwicklung mit Zend Framework 2
Web Development with Zend Framework 2
Persistenz in PHP mit Doctrine 2 ORM
PHP Data Persistence with Doctrine 2 ORM

Contents
Early Access Edition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Introduction . . . . . . . . . . . . . . . .
Who is this book for? . . . . . . . . .
Structure of this book . . . . . . . . .
How you can best work with this book
Found a bug? . . . . . . . . . . . . . .
Conventions used in this book . . . .
Code examples . . . . . . . . . . .
Command line . . . . . . . . . . .

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

2
2
2
3
3
3
3
4

A first look at Zend Framework 3 . . . . . . . . .


Three ways to use the Framework . . . . . . .
Components, components, components! . . . .
Core architecture components (MVC) . . . .
Core architecture components (Middleware)
Important infrastructure components . . . .
Additional components . . . . . . . . . . . .
Getting started . . . . . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

5
5
6
6
6
6
6
8

Building your first Expressive app from scratch


Loading zend-expressive . . . . . . . . . . .
Composer . . . . . . . . . . . . . . . . . . .
Bootstrapping . . . . . . . . . . . . . . . . .
Running the app . . . . . . . . . . . . . . . .

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

10
10
11
12
13

Building your first Expressive app using the skeleton . . . . . . . . . . . . . . . . . . . .

16

Building your first MVC app from scratch . . . . . . . . . . . . . . . . . . . . . . . . . . .

17

Building your first MVC app using the skeleton . . . . . . . . . . . . . . . . . . . . . . . .

18

Consuming individual Framework components . . . . . . . . . . . . . . . . . . . . . . . .

19

Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

20

.
.
.
.
.

Early Access Edition


If you are reading this section, you are holding the early access edition of this book in your hands.
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. 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 book to a minimum. Naturally, I attempt to work
as carefully as possible, but I cannot guarantee absolute freedom from errors at this time. Please
bear with me. If you would like to help me improve this book, feel free to send me comments and
suggestions for improvement at [email protected]. I would greatly appreciate it.

Introduction
Welcome to the latest and greatest version of Zend Framework! Like earlier version of the
framework, Zend Framework 3 aims to further simplify developing web applications using PHP.
Zend Framework 3 allows you to write even more robust, maintainable and extendable enterpriseready PHP applications. It provides you a way to better organize your application code and ships
with many additional utility components making a developers life easier.
When browsing the official framework website (https://framework.zend.com/), you might notice
that Zend Framework 3 usually is just Zend Framework over there. Why is this? Since the
Framework, now in its third version, has completely been decoupled into individual components
with their very own lifecycle, it just makes no real sense to version the overall Framework anymore.
That said, Zend Framework 3 in fact is more a marketing term, while the Framework itself now is
simply named Zend Framework.
Zend Framework 3 keeps a lot of good stuff that was introduced with Zend Framework 2 and at the
same time improves on its weaknesses. It also ships with brand new ideas, components and tools.

Who is this book for?


It is a challenge to write a technical book which finds a balance between theory and practice,
allowing both novices and professionals to get the best out of it. I gladly accepted this task, but
left myself an escape hatch. Later explanation or references are supplied to overcome any of my
straying in a forest of details. No big promises, but I plan to continually revise text and examples:
so keep your purchase up to date! A further challenge is how to address both developers new to
Zend Framework 3 and old hands. For those familiar with Version 1 or 2 I frequently refer to this
predecessor when appropriate, without going into excessive detail. That might also perhaps help
novices, because in this manner they would get a better feeling for why Version 3 is necessary.
I presume that you have basic knowledge of PHP. You do not have to be a PHP expert, particularly
because many native PHP functions became obsolete when one uses Framework techniques. For
example, Session Management, which maps in an object-oriented manner and abstracts some of the
low-level functionality. Hence, if you are accustomed to PHP syntax, have a basic understanding
of the operating principles of PHP applications, and are familiar with common functions of the
language core, you are well prepared. Bear in mind you will also need to use a PHP language
references, readily available on-line.

Structure of this book


This book is not meant to be a compendium. More a pragmatic and practice-oriented introduction
to basic concepts and practical work with Zend Framework 3. In ones progress as a developer, the
2

Introduction

official documentation serves well as a compendium for experienced developers, but is not really
appropriate for use whilst becoming familiar with the subject. Instead, the books objective is to
serve as an (indispensible) reference work for further detailed questions achieving required basic
understanding.
It is structured such that you can read it from the beginning to the end, and that is what you should
do. We will begin with an overview of the Framework, first looking at essential concepts and ideas
forming its essence and differentiating it from its predecessors. On the way, we will repeatedly also
look to the left and right, becoming familiar with the Framework conditions, for example ideas
and discussions behind Frameworks development. Then elucidate the Frameworks most important
components and relationships; peek at how a HTPP request is processed; write our first bit of code;
and an excursion into the Framework environment. We will examine the most important third-party
modules. Modules are a large part of the magic of Zend Framework 3, like it also was already the
case with version 2. Modules can greatly accelerate and simplify application development. Also with
the implementation of the so-called middleware approach now in Zend Framework 3, a new way
of re-using code has been set-up.

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 part of the book 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 some of the lines of code or write some yourself. In the ideal case, you have a system
with a debugger at hand, with which you can follow the Frameworks mode of operation step by
step. Some knowledge of Git and a GitHub account would not hurt anything either, but are not
essential.

Found a bug?
Have you found a bug in the text or code? Please email me at [email protected]. I am thankful
for your feedback and support.

Conventions used in this book


Code examples
The listings in this book have Syntax Highlighting, wherever possible, but do not always conform
to a coding standard; this serves to make them more legible. PHP code is introduced by a <?php, and
a // [..] in the respective listing indicates excluded code fragments.

Introduction

Command line
When a command has to be executed on the command line, this is symbolised by a preceding dollar
sign ($) . The visual feedback of the command is indicated by a preceding greater than sign (>).
Example:
1
2

$ php composer.phar
> Composer version 1.1.3 2016-06-26 15:42:08

A first look at Zend Framework 3


Three ways to use the Framework
Zend Framework 3 allows you to write your applications in two fundamentally different ways, using
two different architectural styles. In addition, you might not want to use Zend Framework 3 as you
app foundation at all, but only use specific Framework components.
First, there is the classic MVC style. If you used earlier version of Zend Framework before,
especially version 2, things will look familiar to you. If you are new to Zend Framework or not
used to other full stack MVC PHP frameworks like Laravel yet: MVC simply means dividing your
app into three interconnected parts, so as to separate internal representations of information (M =
model) from the ways that information is presented (V = view) to or accepted from the user (C =
controller).
If you want to build a MVC structured app, you will base your app on the zend-mvc component and
also leverage a bunch of other related Framework components like the Event Manager and Module
Manager. No worries, we will talk about both in great detail later in this book. While the MVC
approach is still valid and very powerful, its somewhat complex and hard to understand, especially
in the beginning. zend-mvc is not what one would call beginner friendly indeed. Also, it dictates
a specific code structure for your app and makes many assumptions, which may or may not be true
for your specific application.
Because of this, Zend Framework 3 now also includes a so-called micro-framework component
as well. You might use it instead of zend-mvc. Micro-frameworks in general are pretty popular
these days and you will find a lot of them out there. Even the most popular frameworks, like
Symfony or Laravel these days offer an alternative micro-framework right next to their main MVC
framework. And now, also Zend Framework ships with a micro-framework. Its called Expressive,
or zend-expressive. Expressive implements a new approach in structuring an app, using so-called
middleware. Since middleware is PSR-7 compliant, by default, Expressive is also way more open
to work with other libraries and components of other frameworks. You will learn more about
middleware and PSR-7 very soon. For now, keep in mind that Expressive in its core is made to
work well with components provided by other frameworks as well.
Lastly, you may also just cherry-pick certain components out of the Framework to be added to an
(existing) application, E.g. you might want to use zend-from for easier handling of web form creation
and validation. You arent forced to either use zend-mvc or zend-expressive at all to make use of
Zend Framework 3. Think of Zend Framework 3 as a collection of individual components. Just use,
what you like.
All this also means that there is not one true way of using Zend Framework 3. There are different
options for you to get the most out of it.
5

A first look at Zend Framework 3

Components, components, components!


Lets start with a birds-eye view of the Zend Framework 3 components. You will see-whatever
problem you are facing, Zend Framework very likely has you covered. Dont worry if you dont
unterstand all details yet. We will walk through the components later in much greater detail.

Core architecture components (MVC)


zend-mvc: Zend Frameworks event-driven MVC layer. Its going to be in the core of your
application if you want to structure your app based on the MVC pattern.
zend-modulemanager: Modular application system for zend-mvc applications.

Core architecture components (Middleware)


zend-expressive: A micro-framework component as an alternative to zend-mvc.
zend-diactoros: PSR-7 HTTP message implementations.
zend-stratigility: PSR-7 middleware foundation for building and dispatching middleware
pipelines.

Important infrastructure components

zend-router: Flexible routing system for HTTP and console applications.


zend-servicemanager: Factory-Driven Dependency Injection Container
zend-eventmanager: Implement events, signal slots, aspects, and observers!
zend-cache: Caching implementation with a variety of storage options, as well as codified
caching strategies for callbacks, classes, and output.
zend-config: Read and write configuration files.

Additional components
zend-code: Extensions to the PHP Reflection API, static code scanning, and code generation.
zend-component-installer: Composer plugin for injecting modules and configuration providers
into application configuration.
zend-db: Database abstraction layer, SQL abstraction, result set abstraction, and RowDataGateway and TableDataGateway implementations.
zend-debug: Safely dump debug information to HTML.
zend-di: Automated dependency injection and instance manager.
zend-http: HTTP message and header abstractions, and HTTP client implementation. (Not a
PSR-7 implementation.)
zend-loader: Autoloading and plugin loading strategies.

A first look at Zend Framework 3

zend-psr7bridge: PSR-7 <-> zend-http message conversions.


zend-authentication: Authenticate users via a variety of adapters, and provide the authenticated identity to your application.
zend-barcode: Programmatically create and render barcodes as images or in PDFs.
zend-captcha: Generate and validate CAPTCHAs using Figlets, images, ReCaptcha, and more.
zend-console: Build console applications using getopt syntax or routing, complete with
prompts
zend-crypt: Strong cryptography tools and password hashing.
zend-dom: Query HTML and XML documents using XPath or CSS selectors.
zend-escaper: Securely and safely escape HTML, HTML attributes, JavaScript, CSS, and URLs.
zend-feed: Consume and generate Atom and RSS feeds, and interact with Pubsubhubbub.
zend-file: Locate PHP classfiles.
zend-filter: Programmatically filter and normalize data and files.
zend-form: Validate and display simple and complex forms, casting forms to business objects
and vice versa.
zend-hydrator: Serialize objects to arrays, and vice versa.
zend-inputfilter: Normalize and validate input sets from the web, APIs, the CLI, and more,
including files.
zend-i18n: Provide translations for your application, and filter and validate internationalized
values.
zend-json: De/Serialize JSON in PHP, including JavaScript expressions.
zend-json-server: JSON-RPC implementation for PHP.
zend-ldap: Perform LDAP operations, including binding, searching and modifying entries in
an LDAP directory.
zend-log: Robust, composite logger with filtering, formatting, and PSR-3 support.
zend-mail: Parse, create, store, and send email messages, using a variety of storage and
transport protocols.
zend-math: Create cryptographically secure pseudo-random numbers, and manage big integers.
zend-memory: Manage data in an environment with limited memory.
zend-mime: Create and parse MIME messages and parts. including MVC Applications,
Controllers, and Plugins.
zend-mvc-console: Integration between zend-mvc and zend-console.
zend-mvc-i18n: Integration between zend-mvc and zend-i18n.
zend-mvc-plugin-fileprg: Post/Redirect/Get plugin with file upload handling for zend-mvc
controllers.
zend-mvc-plugin-flashmessenger: Plugin for creating and exposing flash messages via zendmvc controllers.
zend-mvc-plugin-identity: Plugin for retrieving the current authenticated identity within
zend-mvc controllers.

A first look at Zend Framework 3

zend-mvc-plugin-prg: Post/Redirect/Get plugin for zend-mvc controllers.


zend-navigation: Manage trees of pointers to web pages in order to build navigation systems.
zend-paginator: Paginate collections of data from arbitrary sources.
zend-permissions-acl: Create, manage, and query access control lists.
zend-permissions-rbac: Provide and query Role-Based Access Controls for your application.
zend-progressbar: Create and update progress bars in different environments.
zend-serializer: Serialize and deserialize PHP structures to a variety of representations.
zend-server: Create Reflection-based RPC servers.
zend-servicemanager-di: zend-di integration for zend-servicemanager
zend-session: Object-oriented interface to PHP sessions and storage.
zend-soap: Create, serve, and access SOAP applications, and parse and generate WSDL.
zend-stdlib: SPL extensions, array utilities, error handlers, and more.
zend-tag: Manipulate and weight taggable items, and create tag clouds.
zend-test: Tools to facilitate unit testing of zend-mvc applications.
zend-text: Create FIGlets and text-based tables.
zend-uri: Object oriented interface to URIs, with facilities for validation.
zend-validator: Validation classes for a wide range of domains, and the ability to chain
validators to create complex validation criteria.
zend-view: Flexible view layer supporting and providing multiple view layers, helpers, and
more.
zend-xmlrpc: Fully-featured XML-RPC server and client implementations.
zend-xml2json: Convert XML documents to JSON.

Getting started
Since Zend Framework 3 essentially is just a compilation of components, one may ask how to kick
in gear? How to glue individual components together to actually get a fully functional app?
Well, you have different options:

Start an Expressive app from scratch


Start an Expressive app using the expressive skeleton application
Start a MVC app from scratch
Start a MVC app using the MVC skeleton application
Cherry picking individual components

We will walk through each of these approaches, mainly as a learning exercise. Later on, you will
always want to use the skeleton applications (think: templates) for your real projects. Why? First off,
wiring up the most fundamental components of Zend Framework 3 to actually produce a running
app involves certain boilerplate code which can and should be re-used, so simply just dont waste

A first look at Zend Framework 3

your time on this. Furthermore, the skeleton applications include several smart solutions to deal
with generic problems, like generating the application config. Even if you consider yourself a PHP
pro, you still might benefit from the code available in the skeleton apps.
However, as you will see, you dont have to use the skeleton apps.

Building your first Expressive app


from scratch
As said earlier, using zend-expressive means building your app based on the micro-framework
component of Zend Framework 3. zend-expressive is the easiest way to get started with Zend
Framework, while it is still capable of scaling to huge enterprise-level applications. Even if you
already know Zend Framework 1 or 2, Expressive will be totally new to you.

Loading zend-expressive
First thing you will need to do is create a new project folder on your disk. If you have PHP 5.4
or newer installed on your system, you may want to serve your app using the built-in web server,
which essentially means, you can create the folder anywhere on your local disk. If you like run
Apache or another web server software on your machine, just make sure to create the new folder in
a location available to your web server.
Within that folder create a file called composer.json with the following contents:
1
2
3
4

{
"require": {
"zendframework/zend-expressive": "^1.0"
},

scripts: {
1
2
3

"serve": "php -S 0.0.0.0:8080 -t public/"


}
}

Next, download composer into that same directory like so:


1

$ wget https://getcomposer.org/composer.phar

Alternatively, you may want to download composer manually and place it in your app folder.

10

Building your first Expressive app from scratch

11

Phar-Archive
A Phar Archive provides the option of making a PHP application available in the form
of a single file. If one looks at the Composer-Repository at GitHub, it becomes clear that
composer does not consist of a single file, as one might think, but that its components are
merely bundled in a Phar Archive for distribution of the application.

Phar Archive and Suhosin


If Suhosin is used on a system, the use of Phar must initially be
explicitly permitted such that the suhosin.ini is extended by the entry
suhosin.executor.include.whitelist=phar. Otherwise, problems can occur in the
execution of Composer commands.

Composer
Composer today is the de facto standard for PHP Dependency Management. The idea behind the
composer is as simple as it is ingenious. A configuration file contains a definition of other code
libraries that an application depends on and from where the respective library can be obtained. In
this case, the application depends on Zend Framework 3s zend-expressive component, as can be
seen by looking in the file composer.json:
1
2
3
4

{
"require": {
"zendframework/zend-expressive": "^1.0"
},

The following command downloads zend-expressive, integrates it in the (empty) application and all
components classes are made available instantly by PHPs autoloading feature:
1
2

$ php composer.phar install


> Installing zendframework/zend-expressive

And thats it! You know have zend-expressive installed in your project.
https://github.com/composer/composer
http://www.hardened-php.net/suhosin/
getcomposer.org/

Building your first Expressive app from scratch

12

Bootstrapping
Next up is creating a bootstrapping script called index.php. Every request handled by your app will
first go through this php file, no matter what the request URL looks like.
In your application root folder, create a new subfolder called public. Within public, create the
index.php with the following contents:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

<?php
use Zend\Expressive\AppFactory;
chdir(dirname(__DIR__));
require 'vendor/autoload.php';
$app = AppFactory::create();
$app->get('/ping', function ($request, $response, $next) {
$response->getBody()->write('Pong!');
return $response;
});
$app->pipeRoutingMiddleware();
$app->pipeDispatchMiddleware();
$app->run();

Lets walk through the most important pieces of index.php. The statement
1

require 'vendor/autoload.php';

enables autoloading of classes downloaded by Composer-no explicit imports necessary anymore.


With
1

$app = AppFactory::create();

a new Expressive app object is created via its factory. $app now acts as the topmost object, in fact
representing the entire app.
Now we make the app respond to a specific URL path:

13

Building your first Expressive app from scratch

1
2
3
4

$app->get('/ping', function ($request, $response, $next)


$response->getBody()->write('Pong!');
return $response;
});

If a GET request is made to /ping, the function given is executed, which in turn for now just sends
back Pong! to the browser. Lets skip the other details of index.php for a minute. We will come
back to it soon.
With
1

$app->run();

the actual request processing is kicked off. At this stage, your application folder should look like this:
public
index.php
vendor
zendframework
(more folders go here)
composer.json
composer.lock
composer.phar

Running the app


Now, run the following command in your application root folder:
1

$ php composer.phar serve

What this does is telling composer to actually run a script defined by you. Remember this piece of
text in composer.json from above?
1
2
3

"scripts": {
"serve": "php -S 0.0.0.0:8080 -t public/"
}

This configuration actually makes the command serve invoke PHPs internal web server on
localhost, port 8080. The document root is configured to be subfolder public, which is exactly
where the index.php file is stored.
(Infos using Apache to follow)
If you open http://localhost:8080/ping in a browser now, you will see an error:

Building your first Expressive app from scratch

1
2

14

Fatal error: Uncaught Error: Class 'Zend\ServiceManager\ServiceManager' not foun\


d

The reason for the error is, that zend-expressive actually depends on two other components which
must be present as well:
A dependency injection (DI) container, e.g. zend-servicemanager
A router, e.g. zend-router
Before we elaborate on what these components actually do and how they work, lets add them to
our app to make it finally run. First, we extend the composer.json file like so:
1
2
3
4
5
6
7
8
9
10

{
"require": {
"zendframework/zend-expressive": "^1.0",
"zendframework/zend-servicemanager": "^3.0",
"zendframework/zend-expressive-zendrouter": "^1.1"
},
"scripts": {
"serve": "php -S 0.0.0.0:8080 -t public/"
}
}

Now running composer again will download the additional components:


1

$ php composer.phar install

Lastly, we need to instantiate a router and a DI container within index.php and use both when
creating the app object:
1
2
3
4
5
6

{:lang="php"}
// [..]
$serviceManager = new ServiceManager();
$router = new ZendRouter();
$app = AppFactory::create($serviceManager, $router);
// [..]

At this point, index.php should looks like this:

Building your first Expressive app from scratch

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

<?php
use Zend\Expressive\AppFactory;
use Zend\ServiceManager\ServiceManager;
use Zend\Expressive\Router\ZendRouter;
chdir(dirname(__DIR__));
require 'vendor/autoload.php';
$serviceManager = new ServiceManager();
$router = new ZendRouter();
$app = AppFactory::create($serviceManager, $router);
$app->get('/ping', function ($request, $response, $next) {
$response->getBody()->write('Hello, world!');
return $response;
});
$app->pipeRoutingMiddleware();
$app->pipeDispatchMiddleware();
$app->run();

If you open http://localhost:8080/ping in a browser again, you now will see:


1

Hello, world!

And thats it! A first sign of life from your app. Congratulations!

15

Building your first Expressive app


using the skeleton

16

Building your first MVC app from


scratch

17

Building your first MVC app using the


skeleton

18

Consuming individual Framework


components

19

Acknowledgements
The cover picture was taken from Freepik. Thanks guys!

20

You might also like