Laravel 创建自定义命令

发布时间:2023-10-12 09:44:20 浏览次数:111

Laravel 创建自定义命令,生成自定义命令文件

  1. 通过laravel的php artisan make:command xx 命令生成命令文件

php artisan make:command MakeService
  1. 在app\Console\Commands 目录下生成了 MakeService.php

<?php
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Console\GeneratorCommand; 

// 重点需要注意的地方,之前是继承的Command 这里记得改下
class MakeService extends GeneratorCommand {
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $name = 'make:service'; // 重点需要注意的地方,之前是$signature这里记得改下 改成$name

    /**
     * The console command description.
     *
     * @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';
    }
}
  1. 建立生成文件的模版

app\Console\Commands\Stubs\services.stub  这个目录建立下这个文件

里面代码内容 (自己改下内容这是我自己的)

<?php
namespace DummyNamespace; 
// 这个DummyNamespace 是一个变量,不清楚可以前往继承的类查看实现
class DummyClass extends BaseService{ 
    // 这个DummyClass 是一个变量,不清楚可以前往继承的类查看实现 
}

写好后就可以方便的使用 php artisan make:service xxxService 命令来生成service文件了


最新文章