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
第67回コンピュータビジョン勉強会CVPR2026読会前編
tsukamotokenji
0
160
ここは地獄!つらい朝会を体験することで、チームとしてのより良い振る舞いに気づくワークショップ / The stand-up meeting from hell in the game industry
scrummasudar
0
220
大量データに対しても、生成AIを用いてリーズナブルにデータ加工をしたい!Databricksのai_queryについて調べてみた
kamoshika
1
280
「守りたい体験」を渡すだけで E2E を生成させられるようになった話
hinac0
2
1k
Playwright × AI Agent でE2Eテストはどう変わるか AI駆動テストの可能性と実用検証の結果
taiga7543
2
790
2026年のソフトウェア開発を考える(2026/07版) / Agentic Software Engineering 2026-07 Findy Edition
twada
PRO
25
11k
人とエージェントが高め合う協業設計
kintotechdev
0
750
副作用のある Lambda でも Lambda Power Tuning は使えるのか / lambda-power-tuning-side-effects
koukihosaka
1
140
アップデートで何が変わった?デモで学んで使いこなすIBM Bob2.0
muehara
0
230
Multicaで30個のミニプロジェクトをAIエージェント運用して見えてきたこと
eiei114
1
620
kaonavi Tech Night#1
kaonavi
0
160
複数プロダクトで進めるAI機能実装 ── 実践から得たリアルな学びとロードマップ実現への挑戦 / AICon2026_yanari
rakus_dev
1
270
Featured
See All Featured
RailsConf 2023
tenderlove
30
1.5k
HTML-Aware ERB: The Path to Reactive Rendering @ RubyCon 2026, Rimini, Italy
marcoroth
3
360
A Modern Web Designer's Workflow
chriscoyier
698
190k
A Soul's Torment
seathinner
6
3.1k
Sam Torres - BigQuery for SEOs
techseoconnect
PRO
0
440
Visual Storytelling: How to be a Superhuman Communicator
reverentgeek
2
590
Why You Should Never Use an ORM
jnunemaker
PRO
61
9.9k
16th Malabo Montpellier Forum Presentation
akademiya2063
PRO
0
280
From Legacy to Launchpad: Building Startup-Ready Communities
dugsong
0
270
Building Experiences: Design Systems, User Experience, and Full Site Editing
marktimemedia
0
560
Crafting Experiences
bethany
1
230
[Rails World 2023 - Day 1 Closing Keynote] - The Magic of Rails
eileencodes
38
2.9k
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の枠内に収まっているのか?(笑