SlideShare una empresa de Scribd logo
1 de 57
HTTP Middlewares in PHP
http://igor.io @igorwhiletrue
@eugene_dounar
Interface?
interface A {
function doSomething();
function doSomethingElse();
}
Универсальный интерфейс
find src -name '*.php' |
grep -iv tests |
cut -f2- -d/ |
cut -f1 -d. |
awk '{ print length, $0 }' |
sort -n |
tr /  ;
nc
xinetd
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

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

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

Destacado

Обзор Drupal 8 by Andrei Khalipau, Kostya Halipov and Егор Богатырёв
Обзор Drupal 8 by Andrei Khalipau, Kostya  Halipov and Егор БогатырёвОбзор Drupal 8 by Andrei Khalipau, Kostya  Halipov and Егор Богатырёв
Обзор Drupal 8 by Andrei Khalipau, Kostya Halipov and Егор Богатырёв
Minsk PHP User Group
 

Destacado (8)

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

Similar a HTTP Middlewares in PHP by Eugene Dounar

Java web programming
Java web programmingJava web programming
Java web programming
Ching Yi Chan
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
Iftekhar Eather
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript
Qiangning Hong
 

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

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

Último

%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 

Último (20)

%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 

HTTP Middlewares in PHP by Eugene Dounar