在 laravel 中可通过 Artisan 创建自定义命令(如 make:service)生成符合团队规范的代码结构,需定义签名、描述、模板逻辑及注册命令。

在 Laravel 中,可以通过 Artisan 命令行 工具 创建自定义模板命令,快速生成项目中常用的代码结构(如 Model、Service、Repository 等)。虽然 Laravel 提供了默认的 make 命令,但我们可以自定义模板和命令来适配团队开发规范。
创建自定义 Artisan 命令
使用内置命令生成一个命令类:
php artisan make:command MakeServiceCommand
该命令会在 app/console/Commands 目录下创建 MakeServiceCommand.php 文件。
定义命令签名与描述
打开刚创建的命令文件,设置 signature 和 description:
protected $signature = 'make:service {name}'; protected $description = 'Create a new service class';
这里 {name} 是参数,表示服务类名称。
立即学习“PHP 免费学习笔记(深入)”;
编写模板逻辑
在 handle() 方法中实现文件生成逻辑:
- 读取自定义模板文件内容
- 替换占位符(如类名)
- 写入目标文件
示例代码:
public function handle() { $name = $this->argument('name'); $path = app_path("Services/{$name}.php"); if (file_exists($path)) {$this->error("Service {$name} already exists!"); return false; } $this->makeDirectory($path); file_put_contents($path, $this->buildClass($name)); $this->info("Service {$name} created successfully."); } protected function buildClass($name) {$stub = file_get_contents(app_path('Console/Stubs/service.stub')); return str_replace(['{{class}}'], [$name], $stub); } protected function makeDirectory($path) {if (! is_dir(dirname($path))) {mkdir(dirname($path), 0755, true); } }
准备模板文件
在 app/Console/Stubs/ 创建 service.stub 模板文件:
<?php namespace AppServices; class {{class}} {// Your service logic here}
运行命令时,{{class}} 会被实际类名替换。
注册命令
将命令添加到 app/Console/Kernel.php 的 $commands 数组中:
protected $commands = [AppConsoleCommandsMakeServiceCommand::class,];
执行自定义命令:
php artisan make:service UserService
将在 app/Services/UserService.php 生成对应类。
基本上就这些。通过这种方式可以扩展出 make:repository、make:request 等符合项目结构的命令,提升开发效率。
以上就是