Laravel自定義Make命令生成Service類

houxin發表於2021-05-09

環境說明

我使用的環境是:Laravel Framework 8.40.0

C:\www\wwwroot\laravel8>php artisan --version
Laravel Framework 8.40.0

一、製作命令檔案

前期知識的相關製作的教程,請參考我的另一篇部落格Laravel自定義Make命令生成目標類

  1. 執行如下命令

     php artisan make:command MakeService

    生成Console/Commands/MakeService.php命令檔案。

  2. 修改繼承類
    把繼承類修改成GeneratorCommand,該類的名稱空間為Illuminate\Console\GeneratorCommand
    刪除例項化方法,handle函式
    實現一個方法getStub

  3. 設定name屬性。
    修改$signature屬性為name屬性,並設定命令:

     protected $name = 'make:service';
  4. 設定type屬性值
    type型別設定,我們生成的是service,所以我們設定的屬性就是Service

     protected $type = 'Service';

    type型別是自己去定義的,本身沒有特殊含義,可以不用設定。

    type屬性值僅僅在建立錯誤的時候,給你一個友好的提示,如下所示:

     C:\www\wwwroot\laravel8>php artisan make:service TestService
     already exists!
    
     C:\www\wwwroot\laravel8>php artisan make:service TestService
     Service already exists!

    第一個是沒有設定type屬性的效果,第二個是設定了type屬性的效果。

    官方使用的type有:Controller,Middleware,Cast,Channel…

    根據自己的需要修改其他的屬性

  5. 設定Stub的位置和命令空間
    Stub的位置是在根目錄下Stubs/service.stub裡面。
    名稱空間在app目錄下Services裡面。

例項程式碼如下:

<?php

namespace App\Console\Commands;

use Illuminate\Console\GeneratorCommand;

class MakeService extends GeneratorCommand
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'make:service';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '生成service物件類';

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

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

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

二、製作Stub檔案

我的service檔案目前不需要繼承或者依賴什麼類。所以,相對的比較簡單。如果你有特別的需要,可以進行擴充套件操作。

例項程式碼如下:

<?php

namespace DummyNamespace;

class DummyClass
{
    //
}

DummyClassDummyNamespace在繼承的GeneratorCommand類內部會被自動替換成自動生成的類名和設定的名稱空間。

建議這種寫法,可以使用編輯器的語法提示,獲得更友好的提示效果。
另外,你也可以使用Larave內建的{{ class }}{{ namespace }}寫法。

三、測試Service生成

執行以下命令

php artisan make:service IndexService

能正常生成成功

C:\www\wwwroot\laravel8>php artisan make:service IndexService
Service created successfully.

生成的檔案的目錄是app/Services/IndexService.php,生成的檔案如下:

<?php

namespace App\Services;

class IndexService
{
    //
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章