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

PSRにのっかってバックエンドサーバを書く / Write a backend server using PSR

Hiroya-W
January 25, 2024

PSRにのっかってバックエンドサーバを書く / Write a backend server using PSR

Hiroya-W

January 25, 2024
Tweet

More Decks by Hiroya-W

Other Decks in Technology

Transcript

  1. スーパーグローバル変数 6 n PHPのどこからでもアクセスできる 変数 • $_SERVER, $_GET, $_POSTなど •

    e.g., http://localhost:8080/index?userId=123 n 連想配列なので… • アクセスする前にキーが存在するかどうかを チェックする必要がある • 再代入可 • 適当な運用をするとヤバい😇
  2. 9 PSR-7: HTTP message interfaces interface MessageInterface { public function

    getHeaders(): array; public function withAddedHeader(string $name, $value): MessageInterface; public function getBody(): StreamInterface; public function withBody(StreamInterface $body): MessageInterface; //… } interface RequestInterface extends MessageInterface { public function getMethod(): string; public function getUri(): UriInterface; //… }
  3. PSR-17: HTTP Factories 13 n HTTP Message objectを作るための Factoryのインターフェース •

    Factoryがインスタンス化する • プログラマはnew Request()とか書かない代わりに Factoryを使う interface RequestFactoryInterface { public function createRequest( string $method, $uri ): RequestInterface; } interface ResponseFactoryInterface { public function createResponse( int $code = 200, string $reasonPhrase = ’’ ): ResponseInterface; }
  4. PSR-7, PSR-17の実装 15 n PSRの実装はあるのでそれを 利用する • ただし、どの実装を選んでも、インターフェース が共通なのでコードへの影響が無く差し替えが 可能なところが嬉しい!

    • https://github.com/Nyholm/psr7 (おすすめ) • https://github.com/guzzle/psr7 • https://github.com/laminas/laminas-http • https://github.com/slimphp/Slim-Psr7 https://github.com/Nyholm/psr7/blob/master/src/Factory/Psr17Factory.php
  5. 26

  6. 31 Webアプリケーションの処理のイメージ Request Middleware 1 例)リクエストの バリデーション Middleware N Router

    Controller 例)ユーザログイン /helloに対応する Controllerを呼び出す レスポンスを作る GET /hello Response HTTP Status: 200 Body: ‘{“status”: “success”}'
  7. PSR-15 HTTP Server Request Handlers 33 n RequestHandlerInterface • PSR-7のRequestを受け取ってResponseを

    返す n MiddlewareInterface • Requestを受け取って処理した後、 RequestHandlerに渡す • 結果としてResponseが返される interface RequestHandlerInterface { public function handle( ServerRequestInterface $request ): ResponseInterface; } interface MiddlewareInterface { public function process( ServerRequestInterface $request, RequestHandlerInterface $handler ): ResponseInterface; }
  8. 37 今回のWebアプリケーション Request Middleware 1 リクエストの バリデーション Middleware N Router

    Controller ユーザログイン 対応するControllerを 呼び出す レスポンスを作る GET /hello Response HTTP Status: 200 Body: ‘{“status”: “success”}'
  9. 40 今回のWebアプリケーション Request Middleware 1 リクエストの バリデーション Middleware N Router

    Controller ユーザログイン 対応するControllerを 呼び出す レスポンスを作る GET /hello Response HTTP Status: 200 Body: ‘{“status”: “success”}' Relay
  10. PSRにのっかってバックエンドサーバを書く n バックエンドサーバとして必要な機能を実装してみた n PSRで定義されるインターフェースを使う • 疎結合な実装ができる • いろんなライブラリを組み合わせて活用できる n

    とはいえ、PSRを使っているものはまだまだ少ない印象 • お試しで作ってみて、その後放置されてるライブラリが多い? • 個人的にはとっても良さそうだったので、色々試行錯誤してみようと思う 52