LoginSignup
15
5

More than 3 years have passed since last update.

Laravel7 make:xxx コマンドを作ってひな形ファイルを生成する

Posted at

プロジェクト特有のクラスのひな形を生成するコマンドを作りたいという要望がよく上がります。
そんな時のためにコマンドを自作する手順をご紹介します。

既存のテンプレートをカスタマイズしたい場合は下記の記事をご覧ください。

手順

$ php artisan make:command UseCaseMakeCommand

app/Console/Commands/UseCaseMakeCommand.php ファイルが生成されます。

app/Console/Commands/UseCaseMakeCommand.php

app/Console/Commands/UseCaseMakeCommand.php
<?php declare(strict_types=1);

namespace App\Console\Commands;

use Illuminate\Console\GeneratorCommand as Command;

class UseCaseMakeCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'make:usecase';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new UseCase class';

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'UseCase';

    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        return $this->laravel->basePath(trim('/stubs/usecase.stub', '/'));
    }

    /**
     * Get the default namespace for the class.
     *
     * @param  string  $rootNamespace
     * @return string
     */
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace . '\UseCase';
    }
}

stubs/usecase.stub

stubs/usecase.stub
<?php declare(strict_types=1);

namespace {{ namespace }};

final class {{ class }}
{
    /**
     * Create a new usecase instance.
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the usecase command.
     */
    public function handle()
    {
        //
    }
}

使い方

$ php artisan make:usecase User/SampleUseCase

app/UseCase/User/SampleUseCase.php ファイルが生成されます。

app/UseCase/User/SampleUseCase.php
<?php declare(strict_types=1);

namespace App\UseCase\User;

final class SampleUseCase
{
    /**
     * Create a new usecase instance.
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the usecase command.
     */
    public function handle()
    {
        //
    }
}

参考

15
5
1

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
15
5