Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
20230315のPHP勉強会(Slimをオススメしてみる)
Search
gallu
March 15, 2023
Technology
280
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
20230315のPHP勉強会(Slimをオススメしてみる)
gallu
March 15, 2023
More Decks by gallu
See All by gallu
日付四方山話
gallu
0
79
セッションで遊んでみた
gallu
0
79
Slimをオススメしてみる ディレクトリ構造
gallu
0
600
Slimをオススメしてみる ControllerとContainer
gallu
0
390
20230215PHP勉強会.pdf
gallu
0
71
PHP 来歴のトリヴィア
gallu
0
130
HTTPを振り返ってみる
gallu
0
65
Other Decks in Technology
See All in Technology
reFACToring
moznion
0
180
キャリアLT会#3
beli68
2
240
そのドキュメント、自動化しませんか?
yuksew
1
410
生成 AI 時代にいま一度「問い合わせ」について考えてみる
kazzpapa3
1
130
AIコード生成×サプライチェーン攻撃 — PHPが直面する“二重の信頼問題
shinyasaita
0
450
ゴールデンパスは敷いただけでは道にならない ─ 企画部門のエンジニアが技術標準を事業価値に変えるまで
mhrtech
1
260
大量データに対しても、生成AIを用いてリーズナブルにデータ加工をしたい!Databricksのai_queryについて調べてみた
kamoshika
1
280
10年目を迎えた「ABEMA」がどのように AI 活用を推進して、AI 駆動開発にシフトしているのか / How ABEMA, entering its 10th year, is promoting the use of AI and shifting toward AI-driven development
miyukki
0
370
AI時代のPlaywright活用(システムテストを自動化する ー 実行エンジンにPla ywrightを選んだ理由)
ynisqa1988
2
930
”AIを使う” から ”AIに任せる” へ ─ 開発プロセスを再設計してAIを組織標準にするまで
cyberagentdevelopers
PRO
1
140
AI_Dev_Day_製造業領域でのAI活用から見た活用の罠と成功に導く実践知.pdf
kintotechdev
0
160
伝票作成AIエージェントを支える、LLMOpsとインフラの選択肢 / AICon2026_takeda
rakus_dev
0
260
Featured
See All Featured
Why Mistakes Are the Best Teachers: Turning Failure into a Pathway for Growth
auna
0
190
Chasing Engaging Ingredients in Design
codingconduct
0
240
Skip the Path - Find Your Career Trail
mkilby
1
170
The Invisible Side of Design
smashingmag
301
52k
Navigating Algorithm Shifts & AI Overviews - #SMXNext
aleyda
1
1.5k
Deep Space Network (abreviated)
tonyrice
0
230
The Language of Interfaces
destraynor
162
27k
sira's awesome portfolio website redesign presentation
elsirapls
0
310
Optimizing for Happiness
mojombo
378
71k
XXLCSS - How to scale CSS and keep your sanity
sugarenia
249
1.3M
Reality Check: Gamification 10 Years Later
codingconduct
0
2.2k
Raft: Consensus for Rubyists
vanstee
141
7.6k
Transcript
Slimをオススメしてみる by がる
自己紹介 古庄と申します 「がる(gallu)」というハンドルでふらついております 本職は技術者です。現役プログラマーやってます バックエンド系なので、インフラとかDBとかも一通り
最近はPM業も多いですねぇ あわせて、教育とか色々
Slimいいよ!! https://www.slimframework.com/ Slim is a PHP micro framework
that helps you quickly write simple yet powerful web applications and APIs. Slim は、シンプルかつ強力な Web アプリケーションと API をすばやく作 成するのに役立つ PHP マイクロ フレームワークです。(Google) Slimは、シンプルかつパワフルなWebアプリケーションやAPIを素早く作 成できるPHPマイクロフレームワークです。(DeepL) Slimいいです!! micro framework いいです!! シンプルでいいです!! っていう個人の感想と妄想を垂れ流してみます(笑
実際どんな所が好きなのか? 軽量(なので早い) メモリは、なんだかんだ無視しにくいリソースです 手元で var_dump(memory_get_peak_usage(true)) 仕込んだ結果
Slim: 2,097,152 / Laravel: 16,777,216 学習コストが(とりあえず)低い 「とりあえず」(笑 「素のPHPのみ」でWebアプリ書ければ大体なんとかなる!! 柔軟性と拡張性がある(というか全部自力で書け) 「全部自分で書け」なので「実装箇所がわかりやすい」(笑 「FWが何をやっているか」が理解しやすい FWのコードもコンパクトなので、読みやすいです 「コンパクトだから読みやすいのか?」って欺瞞は棚の上にw
なにはともあれ Slimの魅力が十分に伝わったところで(強引) installと実装の基本を見ていきましょう!!
素install 公式に出している「slim-skeleton」ってのもあるのですが Slim3の頃とSlim4の時で、色々ごっそり違うんですよねぇ 好み的にはSlim3の頃のほうが好きだったかも ただSlim4のSkeleton、DDDとか意識しているっぽいんですよね
今回は「できるだけすっぴん」で導入していきます
まずは適当なディレクトリで最低限をinstall composer require slim/slim composer require slim/psr7
公開用ディレクトリ作成 mkdir public index.phpを書く(公式サイトのコピペ) 次のページに記載 動かしてみる php -S 0.0.0.0:8080 -t public public/index.php http://ドメイン名/hello/gallu
public/index.php <?php use Psr¥Http¥Message¥ResponseInterface as Response; use Psr¥Http¥Message¥ServerRequestInterface as
Request; use Slim¥Factory¥AppFactory; require __DIR__ . '/../vendor/autoload.php'; $app = AppFactory::create(); $app->get('/hello/{name}', function (Request $request, Response $response, array $args) { $name = $args['name']; $response->getBody()->write("Hello, $name"); return $response; }); $app->run();
これでとりあえず「 /hello/適当な名前 」のURLでSlimが 動くようになります!! とってもシンプル!!!! https://github.com/gallu/Slim- SimpleSkeleton/tree/less_than_minimum
流石にルーティングくらいは別ファイルに 「全部index.phpに書く」とか色々正気ではないので、切り 分けます まずは「ルーティングを書くファイルを入れるためのディ レクトリ」を作成します。なんでもよいですが、今回は(後 で色々な設定も入れようかと思ってるので)configって名 前に
mkdir config index.phpの一部をconfig内のファイル(routes.php)に切り 出します
元のpublic/index.php <?php use Psr¥Http¥Message¥ResponseInterface as Response; use Psr¥Http¥Message¥ServerRequestInterface as
Request; use Slim¥Factory¥AppFactory; require __DIR__ . '/../vendor/autoload.php'; $app = AppFactory::create(); $app->get('/hello/{name}', function (Request $request, Response $response, array $args) { $name = $args['name']; $response->getBody()->write("Hello, $name"); return $response; }); $app->run();
public/index.php <?php use Slim¥Factory¥AppFactory; require __DIR__ . '/../vendor/autoload.php'; $app
= AppFactory::create(); // ルーティングの読み込み require __DIR__ . '/../config/routes.php'; $app->run();
config/routes.php <?php declare(strict_types=1); use Psr¥Http¥Message¥ResponseInterface as Response; use Psr¥Http¥Message¥ServerRequestInterface
as Request; // 初期に書いてあるルーティング $app->get('/hello/{name}', function (Request $request, Response $response, array $args) { $name = $args['name']; $response->getBody()->write("Hello, $name"); return $response; });
同じように「 /hello/適当な名前 」のURLでSlimが動くよう になります!! https://github.com/gallu/Slim- SimpleSkeleton/tree/cut_out_of_routing
ルーティングを追加してみる 現状、 /hello/名前 以外のURLは動かないので。 まぁとりあえず / くらいは追加してみましょう。
元 config/routes.php <?php declare(strict_types=1); use Psr¥Http¥Message¥ResponseInterface as Response; use
Psr¥Http¥Message¥ServerRequestInterface as Request; // 初期に書いてあるルーティング $app->get('/hello/{name}', function (Request $request, Response $response, array $args) { $name = $args['name']; $response->getBody()->write("Hello, $name"); return $response; });
config/routes.php <?php declare(strict_types=1); use Psr¥Http¥Message¥ResponseInterface as Response; use Psr¥Http¥Message¥ServerRequestInterface
as Request; // 初期に書いてあるルーティング $app->get('/hello/{name}', function (Request $request, Response $response, array $args) { $name = $args['name']; $response->getBody()->write("Hello, $name"); return $response; }); // 追加のルーティング $app->get('/', function (Request $request, Response $response, array $args) { $response->getBody()->write("Top Page"); return $response; });
「 / 」のURLでもSlimが動くようになります!! https://github.com/gallu/Slim- SimpleSkeleton/tree/add_routing
Controllerを切り出してみる 普通に考えて「routingん中にコードを書く」とか、常軌を 逸脱しているので いわゆる「Controller」的なクラスを切り出してみましょう まず「Controllerクラスを入れる」ディレクトリを作ります。 これもまぁどこでもよいのですが、慣習も考えてこんな風 にしてみましょう
mkdir -p app/Controller autoloaderとかないと色々面倒なので設定しましょう composer.jsonに追記します(コードは次のページで) requireのバージョンとかちょっと違ってもキニシナイ!! composer dump-autoload
composer.json { "require": { "slim/slim": "^4.11", "slim/psr7": "^1.6" },
"autoload": { "psr-4": { "App¥¥": "app/" } } }
んじゃ、コードを書いていきましょう!!
元 config/routes.php <?php declare(strict_types=1); use Psr¥Http¥Message¥ResponseInterface as Response; use
Psr¥Http¥Message¥ServerRequestInterface as Request; // 初期に書いてあるルーティング $app->get('/hello/{name}', function (Request $request, Response $response, array $args) { $name = $args['name']; $response->getBody()->write("Hello, $name"); return $response; }); // 追加のルーティング $app->get('/', function (Request $request, Response $response, array $args) { $response->getBody()->write("Top Page"); return $response; });
config/routes.php <?php declare(strict_types=1); use Psr¥Http¥Message¥ResponseInterface as Response; use Psr¥Http¥Message¥ServerRequestInterface
as Request; // 初期に書いてあるルーティング $app->get('/hello/{name}', ¥App¥Controller¥HelloController::class . ':index'); // 追加のルーティング $app->get('/', ¥App¥Controller¥HomeController::class);
app/Controller/HelloController.php <?php declare(strict_types=1); namespace App¥Controller; use Psr¥Http¥Message¥ServerRequestInterface as Request;
use Psr¥Http¥Message¥ResponseInterface as Response; class HelloController { // 多分「よくある」系の書き方 public function index(Request $request, Response $response, $args) { $name = $args['name']; $response->getBody()->write("Hello, $name"); return $response; } }
app/Controller/HomeController.php <?php declare(strict_types=1); namespace App¥Controller; use Psr¥Http¥Message¥ServerRequestInterface as Request;
use Psr¥Http¥Message¥ResponseInterface as Response; class HomeController { // XXX 1クラスに「1つしかメソッドを書くつもりがない」場合、こういった書き方もできる public function __invoke(Request $request, Response $response, $args) { // 出力 $response->getBody()->write("Top Page"); return $response; } }
おんなじように動きます!! これで「ふつーのフレームワーク」と大体一緒!! まだ足りない過ぎるけど https://github.com/gallu/Slim- SimpleSkeleton/tree/cut_out_of_controller
Controllerとして許容される形式は? https://www.slimframework.com/docs/v4/objects/routi ng.html#container-resolution 以降に大体書いてあるの ですが $app->get('/', '¥HomeController:home');
$app->get('/', ¥HomeController::class . ':home'); $app->get('/', [¥HomeController::class, 'home']); $app->get('/', ¥HomeAction::class); __invoke() メソッドがある場合 となります あと実際には「関数」も通りますね
その辺のコードをざっくり見てみましょう vendor/slim/slim/Slim/CallableResolver.phpの超訳 private function resolveSlimNotation(string $toResolve): array { [$class,
$method] = :で文字列をsplit(:なかったらmethodには null) if (containerがclassを持ってたら) { $instance = containerからclassのインスタンスをげと インスタンスがげとれなければ例外を投げて終了 } else { if (クラスが存在していなかったら) { if (メソッドがnullじゃなければ) { $class .= '::' . $method . '()'; } $classないよ~、って例外をぶん投げて終了 } $instance = new $class($this->container); } return [$instance, $method]; }
で…… vendor/slim/slim/Slim/CallableResolver.php public function resolve($toResolve): callable { $toResolve =
$this->prepareToResolve($toResolve); if (is_callable($toResolve)) { return $this->bindToContainer($toResolve); } $resolved = $toResolve; if (is_string($toResolve)) { $resolved = $this->resolveSlimNotation($toResolve); $resolved[1] ??= '__invoke'; } $callable = $this->assertCallable($resolved, $toResolve); return $this->bindToContainer($callable); }
なんてあたりで色々やってる感じです。 「配列でも受け入れる」あたりは prepareToResolve()に実 装があります なんていう風に、入り口あたりから軽く「フレームワーク のコードを読む」事を時々すると、良い勉強になるんじゃ ないか、と!!
一区切り まだまだ序の口ですが、しばらくシリーズもの的に「Slim の使い方」をLTしつつ育てていければ、と思います!! 感想とか要望とか突っ込みとか、いただければ幸いで す!! さて、LTの枠内に収まっているのか?(笑