1 新建命令

1、新添加命令

php artisan make:command MakeService
# 执行该命令,将会在app\Console目录下生成Commands目录;
# 同时在 app\Console\Commands 目录下生成 MakeService.php 文件;

2、创建存根目录及文件

# 在 app\Console\Commands目录下创建 Stubs目录;可以直接右键新建文件夹,
mkdir app/Console/Commands/Stubs

# 在该目录下添加名为 services.stub 的文件,
touch app/Console/Commands/Stubs/services.stub

# 完整路径为 app/Console/Commands/Stubs/service.stub

3、编辑文件 services.stub

<?php
 
namespace DummyNamespace;
 
class DummyClass
{
 
}

4、编辑文件 MakeService.php 使用以下内容完全替换。

<?php

namespace App\Console\Commands;

use Illuminate\Console\GeneratorCommand;

class MakeService extends GeneratorCommand
{
    /**
     * 控制台命令名称
     *
     * @var string
     */

    protected $name = 'make:service';

    /**
     * 控制台命令描述
     *
     * @var string
     */

    protected $description = 'Create a new service  class';

    /**
     * 生成类的类型
     *
     * @var string
     */

    protected $type = 'Services';

    /**
     * 获取生成器的存根文件
     *
     * @return string
     */

    protected function getStub()
    {
        return __DIR__ . '/Stubs/services.stub';
    }

    /**
     * 获取类的默认命名空间
     *
     * @param  string  $rootNamespace
     * @return string
     */

    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace . '\Services';
    }
}

2 注册命令

# 编辑 kernel.php 文件中的 protected $commands = [] 属性数组;
# 注册服务使命令生效。
// 记得使用类
// use App\Console\Commands\MakeService;
protected $commands = [
    // 创建服务层
    MakeService::class
]

3 测试命令

# 查看所有的可执行命令
php artisan list
# 测试是否可以创建成功
php artisan make:service TestService
posted on 2020-07-30 12:16  啥也不会的程序猿  阅读(1366)  评论(0编辑  收藏  举报