24

Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier

  • Upload
    others

  • View
    9

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier
Page 2: Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier

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 Publishingprocess. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools andmany iterations to get reader feedback, pivot until you have the right book and build traction onceyou do.

© 2016 Michael Romer

Page 3: Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier

Also By Michael RomerWebentwicklung mit Zend Framework 2

Web Development with Zend Framework 2

Persistenz in PHP mit Doctrine 2 ORM

PHP Data Persistence with Doctrine 2 ORM

Page 4: Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier

Contents

Early Access Edition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Who is this book for? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Structure of this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2How you can best work with this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Found a bug? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Conventions used in this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

Code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Command line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

A first look at Zend Framework 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Three ways to use the Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Components, components, components! . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

Core architecture components (MVC) . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Core architecture components (Middleware) . . . . . . . . . . . . . . . . . . . . . . . 6Important infrastructure components . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Additional components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

Building your first Expressive app from scratch . . . . . . . . . . . . . . . . . . . . . . . . 10Loading zend-expressive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Composer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Bootstrapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Running the app . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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

Page 5: Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier

Early Access EditionIf 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 chaptersare still being written. They will be made available to you as soon as they are finished. It is verypossible that you might find a number of spelling errors or also a bug or two in the code examples inthe early access edition. At the present time no one has supported me with proofreading or editingin order to reduce the number of errors in this book to a minimum. Naturally, I attempt to workas carefully as possible, but I cannot guarantee absolute freedom from errors at this time. Pleasebear with me. If you would like to help me improve this book, feel free to send me comments andsuggestions for improvement at [email protected]. I would greatly appreciate it.

1

Page 6: Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier

IntroductionWelcome to the latest and greatest version of Zend Framework! Like earlier version of theframework, 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 enterprise-ready PHP applications. It provides you a way to better organize your application code and shipswith many additional utility components making a developer’s life easier.

When browsing the official framework website (https://framework.zend.com/), you might noticethat “Zend Framework 3” usually is just “Zend Framework” over there. Why is this? Since theFramework, now in its third version, has completely been decoupled into individual componentswith 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 issimply named “Zend Framework“.

Zend Framework 3 keeps a lot of good stuff that was introduced with Zend Framework 2 and at thesame 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, butleft myself an escape hatch. Later explanation or references are supplied to overcome any of mystraying 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 toZend Framework 3 and “old hands”. For those familiar with Version 1 or 2 I frequently refer to thispredecessor when appropriate, without going into excessive detail. That might also perhaps helpnovices, 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, particularlybecause many “native” PHP functions became obsolete when one uses Framework techniques. Forexample, Session Management, which maps in an object-oriented manner and abstracts some of thelow-level functionality. Hence, if you are accustomed to PHP syntax, have a basic understandingof the operating principles of PHP applications, and are familiar with common functions of thelanguage core, you are well prepared. Bear in mind you will also need to use a PHP languagereferences, readily available on-line.

Structure of this book

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

2

Page 7: Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier

Introduction 3

official documentation serves well as a compendium for experienced developers, but is not reallyappropriate for use whilst becoming familiar with the subject. Instead, the book’s objective is toserve as an (indispensible) reference work for further detailed questions achieving required basicunderstanding.

It is structured such that you can read it from the beginning to the end, and that is what you shoulddo. We will begin with an overview of the Framework, first looking at essential concepts and ideasforming its essence and differentiating it from its predecessors. On the way, we will repeatedly alsolook to the left and right, becoming familiar with the Framework conditions, for example ideasand discussions behind Framework’s development. Then elucidate the Framework’s most importantcomponents 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-partymodules. Modules are a large part of the magic of Zend Framework 3, like it also was already thecase with version 2. Modules can greatly accelerate and simplify application development. Also withthe implementation of the so-called “middleware” approach now in Zend Framework 3, a new wayof 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 activeyourself. Indeed, particularly the first part of the book up to the practice section is already helpfuleven without an opened IDE, but you will have the greatest possible learning success if youreproduce some of the lines of code or write some yourself. In the ideal case, you have a systemwith a debugger at hand, with which you can follow the Framework’s mode of operation step bystep. Some knowledge of Git and a GitHub account would not hurt anything either, but are notessential.

Found a bug?

Have you found a bug in the text or code? Please email me at [email protected]. I am thankfulfor 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 conformto a coding standard; this serves to make them more legible. PHP code is introduced by a <?php, anda // [..] in the respective listing indicates excluded code fragments.

Page 8: Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier

Introduction 4

Command line

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

1 $ php composer.phar

2 > Composer version 1.1.3 2016-06-26 15:42:08

Page 9: Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier

A first look at Zend Framework 3Three ways to use the Framework

Zend Framework 3 allows you to write your applications in two fundamentally different ways, usingtwo different architectural styles. In addition, you might not want to use Zend Framework 3 as youapp 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 notused to other full stack MVC PHP frameworks like Laravel yet: MVC simply means dividing yourapp 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 andalso leverage a bunch of other related Framework components like the Event Manager and ModuleManager. No worries, we will talk about both in great detail later in this book. While the MVCapproach is still valid and very powerful, it’s somewhat complex and hard to understand, especiallyin the beginning. zend-mvc is not what one would call “beginner friendly” indeed. Also, it dictatesa specific code structure for your app and makes many assumptions, which may or may not be truefor your specific application.

Because of this, Zend Framework 3 now also includes a so-called “micro-framework” componentas well. You might use it instead of zend-mvc. Micro-frameworks in general are pretty popularthese days and you will find a lot of them out there. Even the most popular frameworks, likeSymfony or Laravel these days offer an alternative micro-framework right next to their main MVCframework. And now, also Zend Framework ships with a micro-framework. It’s 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 opento work with other libraries and components of other frameworks. You will learn more aboutmiddleware and PSR-7 very soon. For now, keep in mind that Expressive in its core is made towork 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. youmight want to use zend-from for easier handling of web form creationand validation. You aren’t forced to either use zend-mvc or zend-expressive at all to make use ofZend 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 differentoptions for you to get the most out of it.

5

Page 10: Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier

A first look at Zend Framework 3 6

Components, components, components!

Let’s start with a bird’s-eye view of the Zend Framework 3 components. You will see-whateverproblem you are facing, Zend Framework very likely has you covered. Don’t worry if you don’tunterstand all details yet. We will walk through the components later in much greater detail.

Core architecture components (MVC)

• zend-mvc: Zend Framework’s event-driven MVC layer. It’s going to be in the core of yourapplication 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 middlewarepipelines.

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 codifiedcaching 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 injectingmodules and configuration providersinto application configuration.

• zend-db: Database abstraction layer, SQL abstraction, result set abstraction, and RowData-Gateway 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 aPSR-7 implementation.)

• zend-loader: Autoloading and plugin loading strategies.

Page 11: Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier

A first look at Zend Framework 3 7

• zend-psr7bridge: PSR-7 <-> zend-http message conversions.• zend-authentication: Authenticate users via a variety of adapters, and provide the authenti-cated 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 withprompts

• 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 objectsand 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 internationalizedvalues.

• 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 inan 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 andtransport protocols.

• zend-math: Create cryptographically secure pseudo-random numbers, and manage big inte-gers.

• 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-mvccontrollers.

• zend-mvc-plugin-flashmessenger: Plugin for creating and exposing flash messages via zend-mvc controllers.

• zend-mvc-plugin-identity: Plugin for retrieving the current authenticated identity withinzend-mvc controllers.

Page 12: Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier

A first look at Zend Framework 3 8

• 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 chainvalidators to create complex validation criteria.

• zend-view: Flexible view layer supporting and providing multiple view layers, helpers, andmore.

• 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 kickin 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 willalways 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 runningapp involves certain boilerplate code which can and should be re-used, so simply just don’t waste

Page 13: Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier

A first look at Zend Framework 3 9

your time on this. Furthermore, the skeleton applications include several smart solutions to dealwith generic problems, like generating the application config. Even if you consider yourself a PHPpro, you still might benefit from the code available in the skeleton apps.

However, as you will see, you don’t have to use the skeleton apps.

Page 14: Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier

Building your first Expressive appfrom scratchAs said earlier, using zend-expressive means building your app based on the micro-frameworkcomponent of Zend Framework 3. zend-expressive is the easiest way to get started with ZendFramework, while it is still capable of scaling to huge enterprise-level applications. Even if youalready 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.4or 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 runApache or another web server software on your machine, just make sure to create the new folder ina location available to your web server.

Within that folder create a file called composer.json with the following contents:

1 {

2 "require": {

3 "zendframework/zend-expressive": "^1.0"

4 },

“scripts”: {

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

2 }

3 }

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

Page 15: Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier

Building your first Expressive app from scratch 11

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

Phar Archive and SuhosinIf “Suhosin”² is used on a system, the use of Phar must initially beexplicitly permitted such that the suhosin.ini is extended by the entrysuhosin.executor.include.whitelist=phar. Otherwise, problems can occur in theexecution of Composer commands.

Composer

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

1 {

2 "require": {

3 "zendframework/zend-expressive": "^1.0"

4 },

The following command downloads zend-expressive, integrates it in the (empty) application and allcomponents classes are made available instantly by PHP’s autoloading feature:

1 $ php composer.phar install

2 > Installing zendframework/zend-expressive

And that’s it! You know have zend-expressive installed in your project.

¹https://github.com/composer/composer²http://www.hardened-php.net/suhosin/³getcomposer.org/

Page 16: Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier

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 willfirst 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 theindex.php with the following contents:

1 <?php

2 use Zend\Expressive\AppFactory;

3

4 chdir(dirname(__DIR__));

5 require 'vendor/autoload.php';

6

7 $app = AppFactory::create();

8

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

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

11 return $response;

12 });

13

14 $app->pipeRoutingMiddleware();

15 $app->pipeDispatchMiddleware();

16 $app->run();

Let’s 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 factrepresenting the entire app.

Now we make the app respond to a specific URL path:

Page 17: Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier

Building your first Expressive app from scratch 13

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

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

3 return $response;

4 });

If a GET request is made to /ping, the function given is executed, which in turn for now just sendsback “Pong!” to the browser. Let’s skip the other details of index.php for a minute. We will comeback 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 oftext in composer.json from above?

1 "scripts": {

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

3 }

This configuration actually makes the command “serve” invoke PHP’s internal web server onlocalhost, port 8080. The document root is configured to be subfolder “public”, which is exactlywhere 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:

Page 18: Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier

Building your first Expressive app from scratch 14

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

2 d

The reason for the error is, that zend-expressive actually depends on two other components whichmust 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, let’s add them toour app to make it finally run. First, we extend the composer.json file like so:

1 {

2 "require": {

3 "zendframework/zend-expressive": "^1.0",

4 "zendframework/zend-servicemanager": "^3.0",

5 "zendframework/zend-expressive-zendrouter": "^1.1"

6 },

7 "scripts": {

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

9 }

10 }

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 whencreating the app object:

1 {:lang="php"}

2 // [..]

3 $serviceManager = new ServiceManager();

4 $router = new ZendRouter();

5 $app = AppFactory::create($serviceManager, $router);

6 // [..]

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

Page 19: Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier

Building your first Expressive app from scratch 15

1 <?php

2 use Zend\Expressive\AppFactory;

3 use Zend\ServiceManager\ServiceManager;

4 use Zend\Expressive\Router\ZendRouter;

5

6 chdir(dirname(__DIR__));

7 require 'vendor/autoload.php';

8

9 $serviceManager = new ServiceManager();

10 $router = new ZendRouter();

11 $app = AppFactory::create($serviceManager, $router);

12

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

14 $response->getBody()->write('Hello, world!');

15 return $response;

16 });

17

18 $app->pipeRoutingMiddleware();

19 $app->pipeDispatchMiddleware();

20 $app->run();

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

1 Hello, world!

And that’s it! A first sign of life from your app. Congratulations!

Page 20: Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier

Building your first Expressive appusing the skeleton

16

Page 21: Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier

Building your first MVC app fromscratch

17

Page 22: Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier

Building your first MVC app using theskeleton

18

Page 23: Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier

Consuming individual Frameworkcomponents

19

Page 24: Web Development with Zend Framework 3 - Leanpubsamples.leanpub.com/zendframework-sample.pdf · Introduction Welcome to the latest and greatest version of Zend Framework! Like earlier

AcknowledgementsThe cover picture was taken from Freepik. Thanks guys!

20