6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Laravel 10で追加された新機能をチョット試してみた(Laravel Pennant/Process)

Last updated at Posted at 2023-03-15

はじめに

2023年2月14日にLaravel 10がリリースされましたね🥳
新機能がいくつか追加されていましたので
早速少し試してみました!

Laravel Pennant

Laravel Pennantは条件に合わせた機能の使用可否を制御できる機能です。

例えば、特定の条件を満たすユーザのみが特定の機能を使用できるように制御したり、
ランダムに機能を表示させるような制御することが可能です。

今回は管理者限定の機能を想定して試してみます。

まずは手順に沿ってライブラリをインストールします。

[root@a249ad6a6bf4:/var/www# composer require laravel/pennant
Info from https://repo.packagist.org: #StandWithUkraine
./composer.json has been updated
Running composer update laravel/pennant
Loading composer repositories with package information
Updating dependencies
Lock file operations: 1 install, 0 updates, 0 removals
  - Locking laravel/pennant (v1.2.0)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Downloading laravel/pennant (v1.2.0)
  - Installing laravel/pennant (v1.2.0): Extracting archive
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi

   INFO  Discovering packages.  

  laravel/pennant ............................................................................................................................. DONE
  laravel/sail ................................................................................................................................ DONE
  laravel/sanctum ............................................................................................................................. DONE
  laravel/tinker .............................................................................................................................. DONE
  nesbot/carbon ............................................................................................................................... DONE
  nunomaduro/collision ........................................................................................................................ DONE
  nunomaduro/termwind ......................................................................................................................... DONE
  spatie/laravel-ignition ..................................................................................................................... DONE

80 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
> @php artisan vendor:publish --tag=laravel-assets --ansi --force

   INFO  No publishable resources for tag [laravel-assets].  

No security vulnerability advisories found
Using version ^1.2 for laravel/pennant

次にLaravel Pennantの設定ファイルとマイグレーションファイルを複製して
編集が可能なように用意をしておきます。

[root@a249ad6a6bf4:/var/www# php artisan vendor:publish --provider="Laravel\Pennant\PennantServiceProvider"

   INFO  Publishing assets.  

  Copying file [vendor/laravel/pennant/config/pennant.php] to [config/pennant.php] ............................................................ DONE
  Copying directory [vendor/laravel/pennant/database/migrations] to [database/migrations] ..................................................... DONE

最後に複製されたマイグレーションファイルのマイグレーションを行います。
これで準備完了です。

[root@a249ad6a6bf4:/var/www# php artisan migrate

Deprecated: PHP Startup: Use of mbstring.internal_encoding is deprecated in Unknown on line 0

   INFO  Running migrations.  

  2022_11_01_000001_create_features_table ................................................................................................ 45ms DONE

root@a249ad6a6bf4:/var/www#

今回は管理者フラグを想定して
Userモデルにboolean型のadministratorカラムを設けました。

administratorTrueの場合に飲み
「勤怠管理」のメニュー項目がサイドバーに表示されるようにします。

実装はとてもシンプルでした。

まずApp\Providers\AppServiceProviderクラスのbootメソッドへ
機能名と表示条件を定義します。
今回はログインユーザのadministratorを指定しています。

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Models\User;
use Laravel\Pennant\Feature;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Feature::define('attendances-management', function (User $user) {
            return (bool)$user->administrator;
        });
    }
}

次にfeatureディレクティブを使って、
フラグで表示を制御したい範囲を決めます。

<div class="sidebar">
	<ul>
    @feature('attendances-management')
    <li>
		<button>勤怠管理</button>
    </li>
    @endfeature
  </ul>
</div>

たったこれだけで、機能の使用可否の制御ができました!

ディレクティブの他にも

  • Featureクラス
  • HasFeaturesトレイト(モデルクラス)
  • EnsureFeaturesAreActive(ミドルウェア)
    など、様々な箇所で機能の可否制御ができるようです。

権限や機能制限が必要となりそうな
CMSなどの実装においては活用が期待できそうです☺️

Process

Processファサードを使って、外部コマンドを実行できる機能です。

サーバ上の外部コマンドと同様にコマンドを実行して、
その結果を利用したりするのが、ファサードで簡単にできるようです。

例えば、既存のシェルスクリプトをLaravelから呼び出し実行、
その結果に応じて何らかの処理をするといったことができそうですね。

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Process;
use Illuminate\Support\Facades\Log;

class DailyReportCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'batch:daily-report';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Daily Report';

    /**
     * Execute the console command.
     */
    public function handle(): void
    {
        $result = Process::run('sh /var/www/app/Batch/daily-report.sh');
        if ($result->successful()) {
            Log::debug("バッチ処理成功");
        }
    }
}

まとめ

いかがだったでしょうか!
Laravel 10で追加された「Laravel Pennant」、「Processファサード」について
実際に触ってみて取り上げてみました。

実際の開発場面でも使う機会があると思うので、
また調べてみたいなと思います。

告知

最後にお知らせとなりますが、イーディーエーでは一緒に働くエンジニアを募集しております。
詳しくは採用情報ページをご確認ください。
https://eda-inc.jp/recruit/
みなさまからのご応募をお待ちしております。

6
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?