# Lumen8 で API 開発
早くも Lumen はバージョン 8 出ました。そろそろやらないとどんどん進んでいくので追いつくのは難しくなるかなあと思って Lumen8 で API サーバーを作ってみることにしました。
環境
PHP >= 7.3
Laravel Framework Lumen (8.2.3) (Laravel Components ^8.0)
Composer create-project (opens new window) コマンドで api-server という名前のプロジェクト作成
# プロジェクト作成
composer create-project --prefer-dist laravel/lumen api-server
# PHP development server起動
php -S localhost:8000 -t public
# Lumen php artisan 使えるコマンド一覧
Lumen は php artisan serve 使えないけど、他の便利機能は laravel と同様に使える模様
Available commands:
helpDisplay help for a commandlistList commandsmigrateRun the database migrations
auth
auth:clear-resetsFlush expired password reset tokens
cache
cache:clearFlush the application cachecache:forgetRemove an item from the cachecache:tableCreate a migration for the cache database table
db
db:seedSeed the database with recordsdb:wipeDrop all tables, views, and types
make
make:migrationCreate a new migration filemake:seederCreate a new seeder class
migrate
migrate:freshDrop all tables and re-run all migrationsmigrate:installCreate the migration repositorymigrate:refreshReset and re-run all migrationsmigrate:resetRollback all database migrationsmigrate:rollbackRollback the last database migrationmigrate:statusShow the status of each migration
queue
queue:batches-tableCreate a migration for the batches database tablequeue:failedList all of the failed queue jobsqueue:failed-table Create a migration for the failed queue jobs database tablequeue:flushFlush all of the failed queue jobsqueue:forgetDelete a failed queue jobqueue:listenListen to a given queuequeue:restartRestart queue worker daemons after their current jobqueue:retryRetry a failed queue jobqueue:tableCreate a migration for the queue jobs database tablequeue:workStart processing jobs on the queue as a daemon
schedule
schedule:runRun the scheduled commands
# Config オプションはすべて env ファイルに
設定オプションは.envファイルに集中して書くようになります。laravel よりシンプルな設定
ドット記法で設定値取得
// グローバル config ヘルパー
$value = config('app.locale');
// デフォルト値設定
$local = config(['app.locale' => 'ja']);
// 設定ファイル読まれる前のライフサイクルならconfigure使う
$app->configure('app');
// env ファイル値
$debug = env('APP_DEBUG', true);
# ルーティングルール設定
すべてのルーティングルールはroutes/web.phpに書きます。
基本的な使い方
// get・post
$router->get('/', function () {
return 'Hello World';
});
$router->post('welcome', function () {
return ['result' => true,'message' => 'welcome'];
});
// 動的ID
$router->get('user/{id}', function ($id) {
return 'User '.$id;
});
$router->get('posts/{postId}/comments/{commentId}', function ($postId, $commentId) {
return [];
});
# オプションパラメタ
// オプションパラメタ /user[name] will match both /user and /username
$router->get('user[/{name}]', function ($name = null) {
return $name;
});
# 正規表現
// 正規表現
$router->get('user/{name:[A-Za-z]+}', function ($name) {
return $name;
});
# 名前付きルート
asを配列のキーにして名前定義
$router->get('profile', ['as' => 'profile', function () {
//
}]);
$router->get('profile', [
'as' => 'profile', 'uses' => 'UserController@showProfile'
]);
# 使えるメソッド一覧
// 使えるメソッド
$router->get($uri, $callback);
$router->post($uri, $callback);
$router->put($uri, $callback);
$router->patch($uri, $callback);
$router->delete($uri, $callback);
$router->options($uri, $callback);
# Middleware
登録している middleware で制限
$router->group(['middleware' => 'auth'], function () use ($router) {
$router->get('/', function () {
// Uses Auth Middleware
});
$router->get('user/profile', function () {
// Uses Auth Middleware
});
});
# Namespace
$router->group(['namespace' => 'Admin'], function() use ($router)
{
// Using The "App\Http\Controllers\Admin" Namespace...
$router->group(['namespace' => 'User'], function() use ($router) {
// Using The "App\Http\Controllers\Admin\User" Namespace...
});
});
# Prefixe
$router->group(['prefix' => 'admin'], function () use ($router) {
$router->get('users', function () {
// Matches The "/admin/users" URL
});
});
$router->group(['prefix' => 'accounts/{accountId}'], function () use ($router) {
$router->get('detail', function ($accountId) {
// Matches The "/accounts/{accountId}/detail" URL
});
});
# APP_KEY 作成
laravel では php artisan key:generateで APP_KEY 自動生成できますが、Lumen key:generate コマンドがないので手動作成します。
下記の 2 つの方法でランダムの 32 桁英数字が出力されます。
php -r "require 'vendor/autoload.php'; echo \Illuminate\Support\Str::random(32);"
# kJxAhlFSf5uSnAr3C7XreM05Esq4kN98
php -r "echo md5(uniqid()).\"\n\";"
# 5b0af285bc890daecc52458c7949a71c
出力されたランダム文字列をコピーして .env に貼り付けます。
参考Lumen Micro Framework => php artisan key:generate (opens new window)