Laravel 8 利用Command命令创建自定义文件

一、先用make:command命令创建一个命令文件

php artisan make:command ServicesCommand

二、这样会在app\Console\Commands下生成一个ServicesCommand文件

<?php

namespace App\Console\Commands;

use Illuminate\Console\GeneratorCommand;

// 修改继承的基类为GeneratorCommand
class ServicesCommand extends GeneratorCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $name = 'make:service'; // 设置命令

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new service'; // 设置描述

    /**
     * The console command type.
     */
    protected $type = 'service'; // 生成的时候提示类型


    // 生成文件所依赖的模板,可自行设置
    // 我这里把文件放在了同级别Stubs目录下
    protected function getStub()
    {
        return __DIR__.'/Stubs/CreateService.stub';
    }

    // 模板里需要用到的命名空间
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace.'\Services';
    }
}

三、创建Stubs\CreateService.stub文件

<?php

namespace {{ namespace }};

class {{ class }}
{
  // 可自行添加需要的代码      
}

四、测试

// 查看是否有命令
php artisan list

// 创建测试
php artisan make:service TestService

五、其他

  低版本需要在Commands\Kernel的 commands属性 里注册类。

protected $commands = [
  ServicesCommand::class,      
];

 

posted @ 2022-01-22 17:38  wish_yang  阅读(557)  评论(0编辑  收藏  举报