Laravel 中通過自定義命令建立 service 服務層檔案
阿新 • • 發佈:2020-07-30
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