HTTP Middlewares in PHP by Eugene Dounar

395 views

Published on

Minsk PHP User Group Meetup #5

Published in: Software, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
395
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
2
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

HTTP Middlewares in PHP by Eugene Dounar

  1. 1. HTTP Middlewares in PHP http://igor.io @igorwhiletrue @eugene_dounar
  2. 2. Interface? interface A { function doSomething(); function doSomethingElse(); }
  3. 3. Универсальный интерфейс
  4. 4. find src -name '*.php' | grep -iv tests | cut -f2- -d/ | cut -f1 -d. | awk '{ print length, $0 }' | sort -n | tr / ;
  5. 5. nc
  6. 6. xinetd
  7. 7. cgi
  8. 8. 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.
  9. 9. script Переменные окружения ENV Заголовки Тело ответа
  10. 10. GET / HTTP/1.1 Host: igor.io Accept: */* REQUEST_METHOD = GET PATH_INFO = / HTTP_HOST = igor.io HTTP_ACCEPT = */* SERVER_NAME = igor.io
  11. 11. Content-Type: text/html <!DOCTYPE html> <html> ... </html>
  12. 12. fcgi
  13. 13. nginx script
  14. 14. Python? WSGI
  15. 15. def application(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) yield 'Hello Worldn'
  16. 16. Ruby?
  17. 17. app = lambda do |env| body = "Hello, World!" [200, { "Content-Type" => "text/plain", "Content-Length" => body.length.to_s }, [body]]end run app
  18. 18. PHP? ?
  19. 19. PHP? sapi
  20. 20. $_SERVER header() echo exit()
  21. 21. 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
  22. 22. Python :) Ruby :) PHP :(
  23. 23. HttpKernelInterface
  24. 24. <?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 );}
  25. 25. <?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 );}
  26. 26. kernel sapi
  27. 27. Why? Обернуть древний код для тестов?
  28. 28. Why? Обернуть древний код для тестов? exit(‘you lose’);
  29. 29. CgiHttpKernel Адаптер CGI реализующий интерфейс HttpKernelInterface
  30. 30. Why? Кэширование?
  31. 31. Why? Кэширование? $kernel = new AppCache($kernel);
  32. 32. Why? Кэширование? varnish $kernel = new AppCache($kernel);
  33. 33. middleware
  34. 34. <?php$app = new CallableHttpKernel(function ($request) { return new Response('Hello World!');});
  35. 35. 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) { ... }}
  36. 36. $app = new Logger( $app, new MonologLogger());
  37. 37. Session Authentication Logger App
  38. 38. Rack middlewares https://github.com/rack/rack/wiki/List-of-Middleware WSGI middlewares http://wsgi.readthedocs.org/en/latest/libraries.html HttpKernel middlewares ?
  39. 39. Идея: Выполнять код до и после обработки каждого запроса
  40. 40. 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; }}
  41. 41. Идея: Выполнять код до и после обработки каждого запроса События?
  42. 42. $blog = new SilexApplication();$blog->get('/', function () { return 'This is the blog!';});$app = new StackUrlMap($app, [ '/blog' => $blog,]); UrlMap
  43. 43. $app = new CallableHttpKernel(function ($request) { $session = $request->getSession(); ...});$app = new StackSession($app); Session
  44. 44. $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
  45. 45. $request->attributes->get('oauth.token');
  46. 46. Простая композиция:
  47. 47. $stack = (new StackBuilder()) ->push('StackSession') ->push('IgorwStackOAuth', [...]) ->push('Foo');$app = $stack->resolve($app);
  48. 48. Middlewares! ● HttpCache ● GeoIp ● Backstage ● Basic Authentication ● CORS ● Firewall ● CookieGuard ● IpRestrict ● OAuth ● Hawk ● StackRobots
  49. 49. More? ● Authentication (~Warden) ● ForceSSL ● Debug toolbar ● ESI ● OpenID ● ...
  50. 50. stackphp.com github.com/stackphp @stackphp “HttpKernel is a lie” by @igorwhiletrue

×