Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Slim Frameworkで始めるPHPのmiddleware

Slim Frameworkで始めるPHPのmiddleware

2017年7月17日、PHPカンファレンス関西2017での発表資料です。
https://2017.kphpug.jp/

YAMAOKA Hiroyuki

July 15, 2017
Tweet

More Decks by YAMAOKA Hiroyuki

Other Decks in Technology

Transcript

  1. &YQSFTT  IUUQFYQSFTTKTDPN  l'BTU VOPQJOJPOBUFE  NJOJNBMJTUXFCGSBNFXPSLGPS /PEFKTz 

    /PEFKTͰҰ൪࢖ΘΕ͍ͯΔ
 XFCΞϓϦέʔγϣϯϑϨʔϜϫʔΫ
  2. )FMMP8PSME const express = require('express'); const app = express(); app.get('/',

    function(req, res) { res.send('Hello World!'); }); app.listen(3000);
  3. NJEEMFXBSFͷྫ const myLogger = function(req, res, next) { console.log('Logged!'); next();

    }; app.get('/', myLogger, function(req, res) { res.send('Hello World!'); });
  4. NJEEMFXBSFͷྫ શ const myLogger = function(req, res, next) { console.log('Logged!');

    next(); }; app.use(myLogger); // શϦΫΤετʹద༻ app.get('/', function(req, res) { res.send('Hello World!'); });
  5. NJEEMFXBSFͷྫʢෳ਺ʣ const auth = function(req, res, next) {}; const logger

    = function(req, res, next) {}; app.get('/', auth, logger, function(req, res) { res.send('Hello World!'); });
  6. NJEEMFXBSFͷྫʢʁʣ const myLogger = function(req, res) { console.log('Logged!'); }; app.get('/',

    function(req, res, next) { res.send('Hello World!'); next(); }, myLogger); // ॲཧ࣮ߦޙʹݺ͹ΕΔ
  7. )FMMP8PSME // autoloadͱ͔use͸লུ… $app = new \Slim\App(); $app->get('/', function($request, $response)

    { $response->getBody() ->write('Hello World!'); return $response; }); $app->run();
  8. NJEEMFXBSFʢؔ਺ʣ function(Request $request, Response $response, callable $next): Response {
 //

    Կ͔લॲཧΛ͢Δ $response = $next($request, $response); // Կ͔ޙॲཧΛ͢Δ return $response; };
  9. NJEEMFXBSFʢΫϥεʣ class ExampleMiddleware { public function __invoke( Request $request, Response

    $response, callable $next ): Response { // …ؔ਺ͷͱ͖ͱಉ͡ } }
  10. DPOUSPMMFS // $app->get('/', ExampleAction::class); class ExampleAction { public function __invoke(

    Request $request, Response $response, array $args): Response
 { return $response; } }
  11. DPOUSPMMFS /** @var \Slim\Views\Twig */ private $view; public fucntion __construct(Twig

    $view) { $this->view = $view; } public function __invoke(Request $request, Response $response, array $args): Response { return $this->view->render($response, 'foo.twig'); }
  12. 1)1ͷNJEEMFXBSFྲّྀ  %PVCMF1BTT  4MJN͸ͬͪ͜  GO SFRVFTU SFTQPOTF OFYU

    SFTQPOTF  4JOHMF1BTT  GO SFRVFTU OFYU SFTQPOTF
  13. -BSBWFMྫ class CheckAge { public function handle( \Illuminate\Http\Request $request, \Closure

    $next) { // Կ͔ॲཧʢલͰ΋ޙΖͰ΋ʣ return $next($request); } } Route::get('/', function() { /* ॲཧ */ }) ->middleware(CheckAge::class);
  14. ;FOE&YQSFTTJWFྫ $helloMiddleware = function ( ServerRequestInterface $request, DelegateInterface $delegate )

    { return new TextResponse('Hello', 200); }; // ͋Δ͍͸MiddlewareInterfaceΛ࣮૷ͨ͠Ϋϥε $app->get('/hello', $hellosMiddleware);