Laravel - 自定義命令 - 創建 service 服務層文件


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM