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
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
Lightning近況報告
kozy4324
0
170
[チョークトーク資料]AWS DevOps Agent を使いこなす / AWS Dev Ops Agent Chalk Talk AWS Summit Japan 2026
kinunori
2
510
【2026年版】 ベクトル検索とEmbedding最前線
mocobeta
14
3.8k
攻撃者視点で考えるDetection Engineering
cryptopeg
3
2k
あなたの知らないPDFのアクセシビリティ
lycorptech_jp
PRO
0
220
AWS Security Hub CSPMの成功・失敗体験
cmusudakeisuke
0
190
2026TECHFRESH畢業分享會 - 葬送的通靈師:化系統與用戶雜訊成行動訊號
line_developers_tw
PRO
0
1.3k
Oracle AI Database@Azure:サービス概要のご紹介
oracle4engineer
PRO
6
2k
iAEONの段階的リアーキテクト戦略 / iAEON's_Gradual_Re-architecture_Strategy
aeonpeople
0
230
When Platform Engineering Meets GenAI
sucitw
0
120
Oracle AI Database@Google Cloud:サービス概要のご紹介
oracle4engineer
PRO
6
1.5k
マルチアカウント環境での コーディングエージェントを使った障害調査が大変なので AIエージェントにReadOnly権限を付与してみた / ReadOnly AI Agents for Multi-Account AWS Incident Response
yamaguchitk333
2
110
Featured
See All Featured
Bioeconomy Workshop: Dr. Julius Ecuru, Opportunities for a Bioeconomy in West Africa
akademiya2063
PRO
1
150
The Straight Up "How To Draw Better" Workshop
denniskardys
239
140k
Lightning Talk: Beautiful Slides for Beginners
inesmontani
PRO
2
580
Believing is Seeing
oripsolob
1
150
Visualizing Your Data: Incorporating Mongo into Loggly Infrastructure
mongodb
49
10k
The #1 spot is gone: here's how to win anyway
tamaranovitovic
2
1.1k
Thoughts on Productivity
jonyablonski
76
5.2k
Designing for Timeless Needs
cassininazir
1
260
Writing Fast Ruby
sferik
630
63k
How Software Deployment tools have changed in the past 20 years
geshan
0
34k
10 Git Anti Patterns You Should be Aware of
lemiorhan
PRO
659
62k
Marketing Yourself as an Engineer | Alaka | Gurzu
gurzu
0
240
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の枠内に収まっているのか?(笑