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
290
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
84
セッションで遊んでみた
gallu
0
79
Slimをオススメしてみる ディレクトリ構造
gallu
0
610
Slimをオススメしてみる ControllerとContainer
gallu
0
400
20230215PHP勉強会.pdf
gallu
0
71
PHP 来歴のトリヴィア
gallu
0
130
HTTPを振り返ってみる
gallu
0
67
Other Decks in Technology
See All in Technology
暗号化?某ファイルストレージはどうなるの!? 3rd Partyとうまく付き合う秘密度ラベル設計
kasada
0
200
Claude Teamプランの コスト最適化を考える
rfdnxbro
0
710
名刺メーカーDevグループ 紹介資料
sansan33
PRO
0
1.2k
Master Dataグループ紹介資料
sansan33
PRO
1
4.8k
Data Hubグループ 紹介資料
sansan33
PRO
0
3.2k
AI駆動開発を組織で促すために
lycorptech_jp
PRO
3
4.5k
医療の現場を変革に挑戦した半年間の軌跡 - PythonとAIで現場を変える / From Code to Care
soudai
PRO
1
620
NANDでも描画したい!
nichica906
3
740
internal/testlog で遊ぼう
rokuosan
0
240
1.5時間を無駄にして学んだwsl2におけるaptとsnapの選択と仕組み
yosaka0123
0
450
8bit CPU 2026
koba789
7
2.9k
AIエージェントのためのデータ設計
daiz21
0
280
Featured
See All Featured
B2B Lead Gen: Tactics, Traps & Triumph
marketingsoph
0
220
Balancing Empowerment & Direction
lara
6
1.2k
A Modern Web Designer's Workflow
chriscoyier
698
190k
We Have a Design System, Now What?
morganepeng
55
8.3k
Color Theory Basics | Prateek | Gurzu
gurzu
0
440
Raft: Consensus for Rubyists
vanstee
141
7.6k
Why You Should Never Use an ORM
jnunemaker
PRO
61
10k
How to build a perfect <img>
jonoalderson
1
5.9k
エンジニアに許された特別な時間の終わり
watany
108
250k
Dealing with People You Can't Stand - Big Design 2015
cassininazir
367
27k
Writing Fast Ruby
sferik
630
63k
Deep Space Network (abreviated)
tonyrice
0
270
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の枠内に収まっているのか?(笑