Laravel 自定义命令及文件生成示例
以构建 Service 层为例进行说明。
第一步,执行相应的终端指令。
php artisan make:command ServiceMakeCommand
第二步,在 app\Console\Commands 目录下会自动生成一个名为 ServiceMakeCommand.php 的文件,需对其内容进行如下修改(注意:
第一点,该类需继承自 GeneratorCommand;
第二点,protected $signature = 'make:service {name}'; 这一行中的 {name} 参数是必须存在的;
<?php
namespace App\Console\Commands;
use Illuminate\Console\GeneratorCommand;
class ServiceMakeCommand extends GeneratorCommand
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'make:service {name}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a service';
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
return __DIR__.'/stubs/service.stub';
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\Services';
}
}
第三点,准备模板文件。
在 app\Console\Commands\ 目录下新建一个名为 stubs 的文件夹,并在其中创建 service.stub 文件,其具体内容为:
<?php
namespace DummyNamespace;
class DummyClass
{
public function __construct()
{
parent::__construct();
}
}
第四步,此时配置已完成。运行 php artisan list 命令,即可在列表中看到新增的命令项。

执行 php artisan make:service BaseService 后,系统将自动生成 BaseService.php 文件。

以上便是关于 Laravel 自定义命令及文件生成的完整示例,希望能为各位提供有价值的参考,也欢迎继续支持本站。