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

使用内置命令生成一个命令类:
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() 方法中实现文件生成逻辑:
示例代码:
Co.MZ 是一款轻量级企业网站管理系统,基于PHP+Mysql架构的,可运行在Linux、Windows、MacOSX、Solaris等各种平台上,系统基于ThinkPHP,支持自定义伪静态,前台模板采用DIV+CSS设计,后台界面设计简洁明了,功能简单易具有良好的用户体验,稳定性好、扩展性及安全性强,可面向中小型站点提供网站建设解决方案。
0
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 App\Services;
class {{class}}
{
// Your service logic here
}
运行命令时,{{class}} 会被实际类名替换。
将命令添加到 app/Console/Kernel.php 的 $commands 数组中:
protected $commands = [
\App\Console\Commands\MakeServiceCommand::class,
];
执行自定义命令:
php artisan make:service UserService
将在 app/Services/UserService.php 生成对应类。
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号