Develop microservices in PHP

by Enrico Zimuel
Principal Software Engineer @ Elastic

PHPDay, Verona, 10th May 2019

About me


...the microservice architectural style is an approach to developing a single application as a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API

- Martin Fowler

Source: Introduction to microservices

Source: Introduction to microservices


  • Separation of concerns
    • Modularity
    • Encapsulation
  • Scalability
    • Horizontally scaling
    • Workload partitioning


  • Network latency
  • Debugging
  • New architecture challenges:
    • Autodiscovery
    • Telemetry
    • Everything needs to be automated

Web APIs

Building a Web API

  • Managing the HTTP request and response
  • Choosing a representation format
  • Choosing an error format
  • Filtering & validating input data
  • Authenticating HTTP requests
  • Authorizing HTTP requests
  • Documentation

HTTP Methods (REST approach)

  • GET: read a resource
  • HEAD: read without body
  • POST: create a resource
  • PUT: replace a resource
  • PATCH: update a resource
  • DELETE: delete a resource
  • OPTIONS: information about a resource

HTTP Status-code

  • Informational 1xx: 100 Continue
  • Successful 2xx: 200 OK, 201 Created, 202 Accepted
  • Redirection 3xx: 301 Moved Permanently, 307 Temporary Redirect
  • Client Error 4xx: 401 Unauthorized, 404 Not Found, 405 Method Not Allowed
  • Server Error 5xx: 500 Internal Server Error, 503 Service Unavailable

Representation format

  • JSON (JavaScript Object Notation)
    in PHP json_encode(), json_decode()
  • XML (eXtensible Markup Language)
    in PHP SimpleXML, libxml, DOM, etc


HAL-JSON (Hypertext Application Language JSON), Internet-Draft

GET /api/user/ezimuel
    "_links": {
        "self": {
            "href": "http://domain/api/user/ezimuel"
        "contacts": [
            { "href": "http://domain/api/user/mwop" },
            { "href": "http://domain/api/user/zeevs" }
    "id": "ezimuel",
    "name": "Enrico Zimuel"

Error format

Problem Details (RFC 7807)

HTTP/1.1 400 Bad Request
Content-Type: application/problem+json
Content-Language: en

    "type": "",
    "title": "Your request parameters didn't validate.",
    "invalid-params": [
            "name": "age",
            "reason": "must be a positive integer"




HTTP message in PHP

Global variables:

  • $_SERVER
  • $_POST
  • $_GET
  • $_FILES
  • $_COOKIE

HTTP functions in PHP

  • http_response_code()
  • header(), header_remove(), headers_list(), headers_sent()
  • setcookie(), setrawcookie()
  • gethostname(), etc

Manage HTTP in PHP

  • PHP does not offer an object representation of HTTP request/response
  • Unfortunately, It's quite hard to manage HTTP messages in PHP!



  • PHP Framework Interop Group (PHP FIG)
  • A working group for defining common standards to interop between PHP frameworks/libraries
  • PHP Standards Recommendations (PSR)
  • More information at


Common interfaces for representing HTTP messages as described in RFC 7230 and RFC 7231, and URIs for use with HTTP messages as described in RFC 3986

PSR-7 interfaces

  • github: psr/http-message
  • Psr\Http\Message\MessageInterface
  • Psr\Http\Message\RequestInterface
  • Psr\Http\Message\ResponseInterface
  • Psr\Http\Message\ServerRequestInterface
  • Psr\Http\Message\StreamInterface
  • Psr\Http\Message\UploadedFileInterface
  • Psr\Http\Message\UriInterface


// Returns an empty array if not found:
$header = $request->getHeader('Accept');
// Returns an empty string if not found:
$header = $request->getHeaderLine('Accept');
// Test for a header:
if (! $request->hasHeader('Accept')) {}
// Get query string parameters
$query = $request->getQueryParams();


  • PSR-7 Request and Response model immutability
  • Messages are modeled as value objects; a change to any value results in a new instance
  • PSR-7 Stream does not model immutability

zendframework/zend-diactoros implements PSR-7


$response = $response->withStatus(418, "I'm a teapot");

$response = $response->withBody($body);

PSR-7 implementation


  • Swoole is an async programming framework for PHP 7
  • PHP extension, install:
    pecl install swoole
  • Released under Apache license 2.0
  • More info at


  • Event-driven, asynchronous programming for PHP
  • Async TCP / UDP / HTTP / Websocket / HTTP2 client/server side API
  • IPv4 / IPv6 / Unixsocket / TCP/ UDP and SSL / TLS support
  • High performance and scalable
  • Fast serializer / unserializer
  • Milliseconds task scheduler

Swoole vs. PHP-FPM

  • Forks a number of worker processes based on CPU core number
  • Fupports Long-live connections
  • Manage and reuse the status in memory
  • Executes Non-blocking code (async, coroutine)

HTTP Server

use Swoole\Http\Server;

$http = new Server("", 9501);

$http->on("start", function ($server) {
    echo "Started at\n";
$http->on("request", function ($request, $response) {
    $response->header("Content-Type", "text/plain");
    $response->end("Hello World\n");


Test: 16K req/sec on CPU i5-2500, 16 GB RAM, PHP 7.2.12, Swoole 4.2.9

Event loop



A function that gets a request and generates a response

function ($request)
    // do something with $request
    return $response;

Delegating middleware

function ($request, callable $delegate)
    // delegating $request to another middleware
    $response = $delegate($request);
    return $response;

Middleware onion

Execution pipeline

Example: cache

function ($request, callable $delegate) use ($cache)
    if ($cache->has($request)) {
        return $cache->get($request);
    $response = $delegate($request);
    $cache->set($request, $response);
    return $response;


Common interfaces for HTTP server request handlers and HTTP server middleware components that use HTTP messages as described by PSR-7

PSR-15: Handler

namespace Psr\Http\Server;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

interface RequestHandlerInterface
    public function handle(
        ServerRequestInterface $request
    ): ResponseInterface;

An handler returns a response, without delegate

PSR-15: Middleware

namespace Psr\Http\Server;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

interface MiddlewareInterface
    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface;

A middleware participates in processing an HTTP message, it may deletegate.


The PHP framework for middleware applications


You can install Expressive using composer:

composer create-project zendframework/zend-expressive-skeleton api


$app->get('/api/ping', function ($request) {
    return JsonResponse(['ack' => time()])

// or implement a RequestHandlerInterface
$app->get('/api/ping', App\Handler\PingHandler::class);


namespace App\Handler;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Zend\Diactoros\Response\JsonResponse;

class PingHandler implements RequestHandlerInterface
    public function handle(
        ServerRequestInterface $request
    ) : ResponseInterface {
        return new JsonResponse(['ack' => time()]);



Route a REST API

$app->route('/api/users[/{id}]', [
], ['GET', 'POST', 'PATCH', 'DELETE'], 'api.users');

// or route each HTTP method
$app->get('/api/users[/{id}]', ..., 'api.users.get');
$app->post('/api/users', ..., '');
$app->patch('/api/users/{id}', ..., 'api.users.patch');
$app->delete('/api/users/{id}', ..., 'api.users.delete');

Tools for Web API

Expressive with Swoole


composer require zendframework/zend-expressive-swoole


vendor/bin/zend-expressive-swoole start

Open your browser at localhost:8080

PHP + Expressive + Swoole

Run a web application from CLI

Simplify the deploy (only 1 container)

A web server (nginx) can be used as load balancer


2-4x faster than Nginx and Apache

Req/sec (mean)
Nginx 1418.23
Apache 1915.62
Swoole 4864.34

Testing environment:
Ubuntu 18.04, Expressive Skeleton 3.2.3, PHP 7.2.12, Nginx 1.14 + FPM,
Apache 2.4.29 + mod_php, Swoole 4.2.9, CPU i5-2500, 16 GB RAM, HD SSD


  • Elasticsearch is a highly scalable open-source full-text search and analytics engine
  • Near Realtime (NRT)
  • Designed for scale (horizontally)
  • Based on Lucene
  • More information here

Elasticsearch & PHP


use Elasticsearch\ClientBuilder;

$client = ClientBuilder::create()->build();
$params = [
    'index' => 'my_index',
    'type' => 'my_type',
    'id' => 'my_id',
    'body' => ['testField' => 'abc']
$response = $client->index($params);
  • Kibana is an open source data visualization plugin for Elasticsearch
  • It provides visualization capabilities on top of the content indexed on an Elasticsearch cluster
  • More information here




Contact me: enrico.zimuel [at]

Follow me: @ezimuel

Creative Commons License
This work is licensed under a
Creative Commons Attribution-ShareAlike 3.0 Unported License.
I used reveal.js to make this presentation.