SlideShare a Scribd company logo
DEVELOPINGWEBAPIS
USINGMIDDLEWAREINPHP7
by
Senior Software Engineer
, a Rogue Wave Company (USA)
, Turin, 15th June 2017
Enrico Zimuel
Zend
ApiConf
ABOUTME
Developer since 1996
Senior Software Engineer at ,
a Company
Core team of and
and international speaker
Research Programmer at
Author of and
Co-founder of
Zend
Rogue Wave
Apigility ZF
TEDx
UvA
books articles
PUG Torino
Developing web APIs using middleware in PHP 7
PHP
PHP: Hypertext Preprocessor
The most popular server-side language: PHP is used by
82.6% of all the websites (source: )
Used by Facebook, Wikipedia, Yahoo, Etsy, Flickr,
Digg, etc
22 years of usage, since 1995
Full OOP support since PHP 5
w3techs.com
PHP7
Released: 3 December 2015
Previous major was , 13 July 2004PHP 5
Skipped PHP 6: Unicode failure
Last release is (8 Jun 2017)7.1.6
PHP7PERFORMANCE
PHP 7 is also faster than !Python 3
BENCHMARK
$a = [];
for ($i = 0; $i < 1000000; $i++) {
$a[$i] = ["hello"];
}
echo memory_get_usage(true);
PHP 5.6 PHP 7
Memory Usage 428 MB 33 MB
Execution time 0.49 sec 0.06 sec
MOVINGTOPHP7
Badoo saved one million dollars switching to PHP 7
( )
Tumblr reduced the latency and CPU load by half
moving to PHP 7 ( )
Dailymotion handles twice more tra c with same
infrastructure switching to PHP 7 ( )
source
source
source
PHP7ISNOTONLYFAST!
Return and Scalar Type Declarations
Improved Exception hierarchy
Many fatal errors converted to Exceptions
Secure random number generator
Authenticated encryption AEAD (PHP 7.1+)
Nullable types (PHP 7.1+)
and !more
WEBAPISINPHP7
HTTPIN/OUT
EXAMPLE
Request:
GET /api/version
Response:
HTTP/1.1 200 OK
Connection: close
Content-Length: 17
Content-Type: application/json
{
"version": "1.0"
}
MIDDLEWARE
A function that gets a request and generates a response
use PsrHttpMessageServerRequestInterface as Request;
use InteropHttpServerMiddlewareDelegateInterface;
function (Request $request, DelegateInterface $next)
{
// doing something with $request...
// for instance calling the delegate middleware $next
$response = $next->process($request);
// manipulate the $response
return $response;
}
This is called lambda middleware.
DELEGATEINTERFACE
namespace InteropHttpServerMiddleware;
use PsrHttpMessageResponseInterface;
use PsrHttpMessageServerRequestInterface;
interface DelegateInterface
{
/**
* @return ResponseInterface;
*/
public function process(ServerRequestInterface $request);
}
DelegateInterface is part of HTTP Middleware proposalPSR-15
Developing web APIs using middleware in PHP 7
EXPRESSIVE2.0
The PHP framework for Middleware applications
PSR-7 HTTP Message support (using )
Support of lambda middleware (PSR-15) and double
pass ($request, $response, $next)
Piping work ow (using )
Features: routing, dependency injection, templating,
error handling
Last release 2.0.3, 28th March 2017
zend-diactoros
zend-stratigility
INSTALLATION
You can install Expressive 2.0 using :composer
composer create-project zendframework/zend-expressive-skeleton api
Choose the default options during the installation
DEFAULT
The skeleton has 2 URL as example: / and /api/ping
The routes are registered in /con g/routes.php
The middleware actions are stored in /src/App/Action
ROUTES
$app->get('/', AppActionHomePageAction::class, 'home');
$app->get('/api/ping', AppActionPingAction::class, 'api.ping');
/con g/routes.php
APIMIDDLEWARE
namespace AppAction;
use InteropHttpServerMiddlewareDelegateInterface;
use InteropHttpServerMiddlewareMiddlewareInterface;
use ZendDiactorosResponseJsonResponse;
use PsrHttpMessageServerRequestInterface;
class PingAction implements MiddlewareInterface
{
public function process(
ServerRequestInterface $request,
DelegateInterface $delegate
) {
return new JsonResponse(['ack' => time()]);
}
}
/src/App/Action/PingAction.php
PIPELINEWORKFLOW
$app->pipe(ErrorHandler::class);
$app->pipe(ServerUrlMiddleware::class);
$app->pipeRoutingMiddleware();
$app->pipe(ImplicitHeadMiddleware::class);
$app->pipe(ImplicitOptionsMiddleware::class);
$app->pipe(UrlHelperMiddleware::class);
$app->pipeDispatchMiddleware();
$app->pipe(NotFoundHandler::class);
/con g/pipeline.php
SERVICECONTAINER
use ZendServiceManagerConfig;
use ZendServiceManagerServiceManager;
$config = require __DIR__ . '/config.php';
$container = new ServiceManager();
$config = new Config($config['dependencies']);
$config->configureServiceManager($container);
$container->setService('config', $config);
return $container;
/con g/container.php
THEEXPRESSIVEAPP
chdir(dirname(__DIR__));
require 'vendor/autoload.php';
call_user_func(function () {
$container = require 'config/container.php';
$app = $container->get(ZendExpressiveApplication::class);
require 'config/pipeline.php';
require 'config/routes.php';
$app->run();
});
/public/index.php
ROUTEARESTAPI
$app->route('/api/users[/{user-id}]', [
AuthenticationAuthenticationMiddleware::class,
AuthorizationAuthorizationMiddleware::class,
ApiActionUserAction::class
], ['GET', 'POST', 'PATCH', 'DELETE'], 'api.users');
// or route each HTTP method
$app->get('/api/users[/{user-id}]', ..., 'api.users.get');
$app->post('/api/users', ..., 'api.users.post');
$app->patch('/api/users/{user-id}', ..., 'api.users.patch');
$app->delete('/api/users/{user-id}', ..., 'api.users.delete');
RESTDISPATCHTRAIT
use PsrHttpMessageServerRequestInterface;
use InteropHttpServerMiddlewareDelegateInterface;
trait RestDispatchTrait
{
public function process(
ServerRequestInterface $request,
DelegateInterface $delegate
) {
$method = strtolower($request->getMethod());
if (method_exists($this, $method)) {
return $this->$method($request);
}
return $response->withStatus(501); // Method not implemented
}
}
RESTMIDDLEWARE
class UserAction implements MiddlewareInterface
{
use RestDispatchTrait;
public function get(ServerRequestInterface $request)
{
$id = $request->getAttribute('user-id', false);
$data = (false === $id) ? /* all users */ : /* user id */;
return new JsonResponse($data);
}
public function post(ServerRequestInterface $request){ ... }
public function patch(ServerRequestInterface $request){ ... }
public function delete(ServerRequestInterface $request){ ... }
}
ApiActionUserAction.php
THANKS!
More info: https://framework.zend.com/blog
Contact me: enrico.zimuel [at] roguewave.com
Follow me: @ezimuel
This work is licensed under a
.
I used to make this presentation.
Creative Commons Attribution-ShareAlike 3.0 Unported License
reveal.js

More Related Content

PDF
Middleware web APIs in PHP 7.x
ODP
My self learing -Php
PDF
A Look at Command Line Swift
PDF
FISE Integration with Python and Plone
DOCX
Software Instructions
ODP
PPTX
drone continuous Integration
Middleware web APIs in PHP 7.x
My self learing -Php
A Look at Command Line Swift
FISE Integration with Python and Plone
Software Instructions
drone continuous Integration

What's hot (20)

PDF
Big Fat FastPlone - Scale up, speed up
ODP
Buildout: creating and deploying repeatable applications in python
PDF
Building RT image with Yocto
PDF
このPHP拡張がすごい!2017
PPT
The future of server side JavaScript
PDF
Drone 1.0 Feature
PDF
Golang Project Layout and Practice
PDF
openPOWERLINK over Xenomai
PPTX
PHP in one presentation
PPTX
Build Python CMS The Plone Way
PPS
Simplify your professional web development with symfony
PDF
Ikazuchi introduction for Europython 2011 LT
PPTX
Go & multi platform GUI Trials and Errors
PDF
Development and deployment with composer and kite
PDF
Using the "pip" package manager for Odoo/OpenERP - Opendays 2014
PDF
Import golang; struct microservice - Codemotion Rome 2015
PDF
GNU Make, Autotools, CMake 簡介
PDF
Don't Fear the Autotools
PDF
Rest, sockets em golang
PDF
I docstools
Big Fat FastPlone - Scale up, speed up
Buildout: creating and deploying repeatable applications in python
Building RT image with Yocto
このPHP拡張がすごい!2017
The future of server side JavaScript
Drone 1.0 Feature
Golang Project Layout and Practice
openPOWERLINK over Xenomai
PHP in one presentation
Build Python CMS The Plone Way
Simplify your professional web development with symfony
Ikazuchi introduction for Europython 2011 LT
Go & multi platform GUI Trials and Errors
Development and deployment with composer and kite
Using the "pip" package manager for Odoo/OpenERP - Opendays 2014
Import golang; struct microservice - Codemotion Rome 2015
GNU Make, Autotools, CMake 簡介
Don't Fear the Autotools
Rest, sockets em golang
I docstools
Ad

Similar to Developing web APIs using middleware in PHP 7 (20)

ODP
An OpenShift Primer for Developers to get your Code into the Cloud (PTJUG)
PDF
The why and how of moving to php 8
PDF
Speed up web APIs with Expressive and Swoole (PHP Day 2018)
PDF
The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016
PDF
The new features of PHP 7
PDF
CodePolitan Webinar: The Rise of PHP
PDF
Cytoscape and External Data Analysis Tools
PDF
Lean Php Presentation
PDF
Unleash your Symfony projects with eZ Platform
PDF
Exploring Async PHP (SF Live Berlin 2019)
PPT
Introduction to web and php mysql
PDF
Php Interview Questions
PDF
Make your application expressive
PPTX
N-API NodeSummit-2017
PDF
N api-node summit-2017-final
PDF
PHP - Programming language war, does it matter
ODP
PHP from the point of view of a webhoster
PDF
Advanced Eclipse Workshop (held at IPC2010 -spring edition-)
PPTX
Ran Mizrahi - Symfony2 meets Drupal8
PPTX
An OpenShift Primer for Developers to get your Code into the Cloud (PTJUG)
The why and how of moving to php 8
Speed up web APIs with Expressive and Swoole (PHP Day 2018)
The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016
The new features of PHP 7
CodePolitan Webinar: The Rise of PHP
Cytoscape and External Data Analysis Tools
Lean Php Presentation
Unleash your Symfony projects with eZ Platform
Exploring Async PHP (SF Live Berlin 2019)
Introduction to web and php mysql
Php Interview Questions
Make your application expressive
N-API NodeSummit-2017
N api-node summit-2017-final
PHP - Programming language war, does it matter
PHP from the point of view of a webhoster
Advanced Eclipse Workshop (held at IPC2010 -spring edition-)
Ran Mizrahi - Symfony2 meets Drupal8
Ad

More from Zend by Rogue Wave Software (20)

PDF
Develop microservices in php
PPTX
Speed and security for your PHP application
PPTX
Building and managing applications fast for IBM i
PDF
Building web APIs in PHP with Zend Expressive
PPTX
To PHP 7 and beyond
PDF
The Sodium crypto library of PHP 7.2 (PHP Day 2018)
PDF
Develop web APIs in PHP using middleware with Expressive (Code Europe)
PPTX
Ongoing management of your PHP 7 application
PDF
The Docker development template for PHP
PDF
The most exciting features of PHP 7.1
PPTX
Unit testing for project managers
PPTX
Deploying PHP apps on the cloud
PPTX
Data is dead. Long live data!
PPTX
Optimizing performance
PPTX
Resolving problems & high availability
PPTX
Developing apps faster
PPTX
Keeping up with PHP
PPTX
Fundamentals of performance tuning PHP on IBM i
PPTX
Getting started with PHP on IBM i
PDF
Continuous Delivery e-book
Develop microservices in php
Speed and security for your PHP application
Building and managing applications fast for IBM i
Building web APIs in PHP with Zend Expressive
To PHP 7 and beyond
The Sodium crypto library of PHP 7.2 (PHP Day 2018)
Develop web APIs in PHP using middleware with Expressive (Code Europe)
Ongoing management of your PHP 7 application
The Docker development template for PHP
The most exciting features of PHP 7.1
Unit testing for project managers
Deploying PHP apps on the cloud
Data is dead. Long live data!
Optimizing performance
Resolving problems & high availability
Developing apps faster
Keeping up with PHP
Fundamentals of performance tuning PHP on IBM i
Getting started with PHP on IBM i
Continuous Delivery e-book

Recently uploaded (20)

PPTX
L1 - Introduction to python Backend.pptx
PDF
Digital Strategies for Manufacturing Companies
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PPTX
history of c programming in notes for students .pptx
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
Transform Your Business with a Software ERP System
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PPTX
Online Work Permit System for Fast Permit Processing
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PPTX
ISO 45001 Occupational Health and Safety Management System
L1 - Introduction to python Backend.pptx
Digital Strategies for Manufacturing Companies
Navsoft: AI-Powered Business Solutions & Custom Software Development
history of c programming in notes for students .pptx
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Softaken Excel to vCard Converter Software.pdf
Understanding Forklifts - TECH EHS Solution
Transform Your Business with a Software ERP System
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Online Work Permit System for Fast Permit Processing
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Operating system designcfffgfgggggggvggggggggg
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
2025 Textile ERP Trends: SAP, Odoo & Oracle
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
ISO 45001 Occupational Health and Safety Management System

Developing web APIs using middleware in PHP 7