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
Sponsored
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
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
77
セッションで遊んでみた
gallu
0
78
Slimをオススメしてみる ディレクトリ構造
gallu
0
590
Slimをオススメしてみる ControllerとContainer
gallu
0
390
20230215PHP勉強会.pdf
gallu
0
70
PHP 来歴のトリヴィア
gallu
0
130
HTTPを振り返ってみる
gallu
0
65
Other Decks in Technology
See All in Technology
2026TECHFRESH畢業分享會 - Lightning Talk - 資料也要 CI/CD? 用 Airbyte 自動化資料同步
line_developers_tw
PRO
0
1.2k
SONiCの統計情報を取得したい
sonic
0
220
AI-DLCを “そのまま導入しなかった”話 ~組織に合わせてアジャストした 私たちの実践共有~
hiroramos4
PRO
0
120
ぼっちではじめた登壇が「51名」「241件」の発信に化けた
subroh0508
0
170
白金鉱業Meetup_Vol.24_「AIエージェントは分けるほど良い」は本当か? / Is it true that “the more you divide AI agents, the better”?
brainpadpr
1
410
2026TECHFRESH畢業分享會 - 葬送的通靈師:化系統與用戶雜訊成行動訊號
line_developers_tw
PRO
0
1.2k
AIのReact習熟度を測る
uhyo
2
640
MCP Appsを作ってみよう
iwamot
PRO
4
690
失敗を資産に変えるClaude Code
shinyasaita
0
710
AIチャット検索改善の3週間
kworkdev
PRO
2
130
Agent Skills設計で柔軟性と硬さのバランスが難しい話
nassy20
0
140
【セミナー資料】Claude Code をセキュアに使うための考え方と設定の勘どころ / Claude Code Webinar 20260616
masahirokawahara
2
410
Featured
See All Featured
Leadership Guide Workshop - DevTernity 2021
reverentgeek
1
310
Documentation Writing (for coders)
carmenintech
77
5.4k
Practical Orchestrator
shlominoach
191
11k
Designing Powerful Visuals for Engaging Learning
tmiket
1
420
brightonSEO & MeasureFest 2025 - Christian Goodrich - Winning strategies for Black Friday CRO & PPC
cargoodrich
3
730
Google's AI Overviews - The New Search
badams
0
1k
What's in a price? How to price your products and services
michaelherold
247
13k
How to build a perfect <img>
jonoalderson
1
5.7k
Applied NLP in the Age of Generative AI
inesmontani
PRO
4
2.3k
Redefining SEO in the New Era of Traffic Generation
szymonslowik
1
340
Claude Code のすすめ
schroneko
67
230k
Color Theory Basics | Prateek | Gurzu
gurzu
0
370
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の枠内に収まっているのか?(笑