SlideShare a Scribd company logo
HTTP Middlewares in PHP
http://igor.io @igorwhiletrue
@eugene_dounar
Interface?
interface A {
function doSomething();
function doSomethingElse();
}
HTTP Middlewares in PHP by Eugene Dounar
HTTP Middlewares in PHP by Eugene Dounar
Универсальный интерфейс
HTTP Middlewares in PHP by Eugene Dounar
find src -name '*.php' |
grep -iv tests |
cut -f2- -d/ |
cut -f1 -d. |
awk '{ print length, $0 }' |
sort -n |
tr /  ;
HTTP Middlewares in PHP by Eugene Dounar
nc
HTTP Middlewares in PHP by Eugene Dounar
HTTP Middlewares in PHP by Eugene Dounar
xinetd
HTTP Middlewares in PHP by Eugene Dounar
cgi
RFC 3875
The Common Gateway Interface (CGI) [22] allows an HTTP [1], [4] server
and a CGI script to share responsibility for responding to client requests.
script
Переменные
окружения
ENV
Заголовки
Тело ответа
GET / HTTP/1.1
Host: igor.io
Accept: */*
REQUEST_METHOD = GET
PATH_INFO = /
HTTP_HOST = igor.io
HTTP_ACCEPT = */*
SERVER_NAME = igor.io
Content-Type: text/html
<!DOCTYPE html>
<html>
...
</html>
fcgi
nginx
script
Python?
WSGI
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/plain')])
yield 'Hello Worldn'
Ruby?
app = lambda do |env|
body = "Hello, World!"
[200, {
"Content-Type" => "text/plain",
"Content-Length" => body.length.to_s
}, [body]]end
run app
PHP?
?
PHP?
sapi
$_SERVER
header()
echo
exit()
php_sapi_name()
➔ aolserver
➔ apache
➔ apache2filter
➔ apache2handler
➔ caudium
➔ cgi (until PHP 5.3)
➔ cgi-fcgi
➔ cli
➔ continuity
➔ embed
➔ isapi
➔ litespeed
➔ milter
➔ nsapi
➔ phttpd
➔ pi3web
➔ roxen
➔ thttpd
➔ tux
➔ webjames
Python :)
Ruby :)
PHP :(
HttpKernelInterface
<?php
namespace SymfonyComponentHttpKernel;use
SymfonyComponentHttpFoundationRequest;use
SymfonyComponentHttpFoundationResponse;interface
HttpKernelInterface{
const MASTER_REQUEST = 1;
const SUB_REQUEST = 2;
public function handle(
Request $request,
$type = self::MASTER_REQUEST,
$catch = true
);}
<?php
namespace SymfonyComponentHttpKernel;use
SymfonyComponentHttpFoundationRequest;use
SymfonyComponentHttpFoundationResponse;interface
HttpKernelInterface{
const MASTER_REQUEST = 1;
const SUB_REQUEST = 2;
public function handle(
Request $request,
$type = self::MASTER_REQUEST,
$catch = true
);}
kernel
sapi
Why?
Обернуть древний код для тестов?
Why?
Обернуть древний код для тестов?
exit(‘you lose’);
CgiHttpKernel
Адаптер CGI реализующий
интерфейс HttpKernelInterface
Why?
Кэширование?
Why?
Кэширование?
$kernel = new AppCache($kernel);
Why?
Кэширование?
varnish
$kernel = new AppCache($kernel);
middleware
<?php$app = new CallableHttpKernel(function ($request) {
return new Response('Hello World!');});
class Logger implements HttpKernelInterface{
private $app;
private $logger;
public function __construct(HttpKernelInterface $app, LoggerInterface $logger)
{
$this->app = $app;
$this->logger = $logger;
}
public function handle(Request $request, ...)
{
$response = $this->app->handle($request, $type, $catch);
$this->log($request, $response);
return $response;
}
private function log(Request $request, Response $response)
{
...
}}
$app = new Logger(
$app,
new MonologLogger());
Session
Authentication
Logger
App
Rack middlewares https://github.com/rack/rack/wiki/List-of-Middleware
WSGI middlewares http://wsgi.readthedocs.org/en/latest/libraries.html
HttpKernel middlewares ?
Идея:
Выполнять код до и после
обработки каждого запроса
class Foo implements HttpKernelInterface{
private $app;
public function __construct(HttpKernelInterface $app)
{
$this->app = $app;
}
public function handle(Request $request, ...)
{
$response = $this->app->handle($request, $type, $catch);
return $response;
}}
Идея:
Выполнять код до и после
обработки каждого запроса
События?
$blog = new SilexApplication();$blog->get('/',
function () {
return 'This is the blog!';});$app = new
StackUrlMap($app, [
'/blog' => $blog,]);
UrlMap
$app = new CallableHttpKernel(function ($request) {
$session = $request->getSession();
...});$app = new StackSession($app);
Session
$app = new IgorwStackOAuth($app, [
'key'=> 'foo',
'secret'=> 'bar',
'callback_url' => 'http://localhost:8080/auth/verify',
'success_url'=> '/',
'failure_url'=> '/auth',]);$app = new StackSession($app);
OAuth
$request->attributes->get('oauth.token');
Простая композиция:
$stack = (new StackBuilder())
->push('StackSession')
->push('IgorwStackOAuth', [...])
->push('Foo');$app = $stack->resolve($app);
Middlewares!
● HttpCache
● GeoIp
● Backstage
● Basic Authentication
● CORS
● Firewall
● CookieGuard
● IpRestrict
● OAuth
● Hawk
● StackRobots
More?
● Authentication (~Warden)
● ForceSSL
● Debug toolbar
● ESI
● OpenID
● ...
stackphp.com
github.com/stackphp
@stackphp
“HttpKernel is a lie” by @igorwhiletrue

More Related Content

PDF
Nette framework (WebElement #28)
PDF
The IoC Hydra - Dutch PHP Conference 2016
PDF
How to send gzipped requests with boto3
PDF
Forget about index.php and build you applications around HTTP!
DOCX
Fidl analysis
PPTX
Speed up your developments with Symfony2
PDF
Building Modern and Secure PHP Applications – Codementor Office Hours with Be...
PDF
Job Queue in Golang
Nette framework (WebElement #28)
The IoC Hydra - Dutch PHP Conference 2016
How to send gzipped requests with boto3
Forget about index.php and build you applications around HTTP!
Fidl analysis
Speed up your developments with Symfony2
Building Modern and Secure PHP Applications – Codementor Office Hours with Be...
Job Queue in Golang

What's hot (20)

PDF
Bootstrapping multidc observability stack
PDF
PPTX
Web2Day 2017 - Concilier DomainDriveDesign et API REST
PDF
Oro meetup #4
PDF
Découvrir dtrace en ligne de commande.
PDF
Keep It Simple Security (Symfony cafe 28-01-2016)
PPTX
Hacking hhvm
PDF
Symfony without the framework
PDF
用 Go 語言打造多台機器 Scale 架構
PDF
Introduction to the Pods JSON API
PDF
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
ODP
nginx mod PSGI
KEY
Perl: Hate it for the Right Reasons
PDF
IoT Best practices
PPTX
Php 7.x 8.0 and hhvm and
ODP
Anyevent
PDF
A Lifecycle Of Code Under Test by Robert Fornal
DOCX
Sadi service
DOCX
Example code for the SADI BMI Calculator Web Service
PPTX
2012: ql.io and Node.js
Bootstrapping multidc observability stack
Web2Day 2017 - Concilier DomainDriveDesign et API REST
Oro meetup #4
Découvrir dtrace en ligne de commande.
Keep It Simple Security (Symfony cafe 28-01-2016)
Hacking hhvm
Symfony without the framework
用 Go 語言打造多台機器 Scale 架構
Introduction to the Pods JSON API
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
nginx mod PSGI
Perl: Hate it for the Right Reasons
IoT Best practices
Php 7.x 8.0 and hhvm and
Anyevent
A Lifecycle Of Code Under Test by Robert Fornal
Sadi service
Example code for the SADI BMI Calculator Web Service
2012: ql.io and Node.js
Ad

Viewers also liked (8)

PDF
Обзор Drupal 8 by Andrei Khalipau, Kostya Halipov and Егор Богатырёв
PDF
responsive | adaptive web design by Dmitry Beynya & Евгений Пась
PPTX
PSR: Standards in PHP by Alex Simanovich
PDF
Symfony2. Unit testing by Vadim Kharitonov
ODP
Dependency Injection in Drupal 8 - Стадник АндрейQweqwe
PDF
Five Things to Look for in Food
PDF
Investment Thesis Fundamentals (April 2016)
Обзор Drupal 8 by Andrei Khalipau, Kostya Halipov and Егор Богатырёв
responsive | adaptive web design by Dmitry Beynya & Евгений Пась
PSR: Standards in PHP by Alex Simanovich
Symfony2. Unit testing by Vadim Kharitonov
Dependency Injection in Drupal 8 - Стадник АндрейQweqwe
Five Things to Look for in Food
Investment Thesis Fundamentals (April 2016)
Ad

Similar to HTTP Middlewares in PHP by Eugene Dounar (20)

KEY
Intro to PSGI and Plack
PDF
WCMTL 15 - Create your own shortcode (Fr)
ODP
PHP pod mikroskopom
PDF
An introduction to PHP 5.4
PDF
Living With Legacy Code
KEY
Java web programming
PPTX
Introducing PHP Latest Updates
PDF
What's New In Laravel 5
ODP
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
PDF
Arquitecturas de microservicios - Medianet Software
PDF
Hexagonal architecture
PPTX
PHP: GraphQL consistency through code generation
PDF
2019 11-bgphp
PDF
Cli the other SAPI confoo11
PDF
Complex Sites with Silex
PDF
Dependency Injection
PDF
関西PHP勉強会 php5.4つまみぐい
PPTX
Java Libraries You Can’t Afford to Miss
PDF
服务框架: Thrift & PasteScript
PDF
A portlet-API based approach for application integration
Intro to PSGI and Plack
WCMTL 15 - Create your own shortcode (Fr)
PHP pod mikroskopom
An introduction to PHP 5.4
Living With Legacy Code
Java web programming
Introducing PHP Latest Updates
What's New In Laravel 5
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Arquitecturas de microservicios - Medianet Software
Hexagonal architecture
PHP: GraphQL consistency through code generation
2019 11-bgphp
Cli the other SAPI confoo11
Complex Sites with Silex
Dependency Injection
関西PHP勉強会 php5.4つまみぐい
Java Libraries You Can’t Afford to Miss
服务框架: Thrift & PasteScript
A portlet-API based approach for application integration

Recently uploaded (20)

PPTX
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
Operating system designcfffgfgggggggvggggggggg
PPT
Introduction Database Management System for Course Database
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PPTX
Odoo POS Development Services by CandidRoot Solutions
PPTX
ai tools demonstartion for schools and inter college
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
history of c programming in notes for students .pptx
PDF
Understanding Forklifts - TECH EHS Solution
PDF
top salesforce developer skills in 2025.pdf
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Softaken Excel to vCard Converter Software.pdf
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Operating system designcfffgfgggggggvggggggggg
Introduction Database Management System for Course Database
VVF-Customer-Presentation2025-Ver1.9.pptx
Odoo POS Development Services by CandidRoot Solutions
ai tools demonstartion for schools and inter college
2025 Textile ERP Trends: SAP, Odoo & Oracle
How to Migrate SBCGlobal Email to Yahoo Easily
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
history of c programming in notes for students .pptx
Understanding Forklifts - TECH EHS Solution
top salesforce developer skills in 2025.pdf

HTTP Middlewares in PHP by Eugene Dounar