创建用于生成自定义类或文件的artisan命令

Mil*_*ari 8 php laravel laravel-5.2

创建用于生成自定义类或文件的工匠命令的最佳方式(或者实际完成方式)是什么?就像php artisan make:console为我们的新工匠命令创建一个php类一样.

从我能想到的,我们有两个选择:

  • 使用php heredoc(或新命令的类文件中的任何字符串)为该新文件添加模板,这非常麻烦.

  • 将模板文件放在某处,读取它,替换必要的文件,然后创建新文件.但我不知道放置模板文件的最佳位置.

那么在Laravel中处理这种情况有最好的做法吗?我用Google搜索,但只有简单的工匠命令创建的文章和文档.

abe*_*ree 13

我知道这个问题有点老了,但是如果您只想创建Laravel已经做过的类似文件,这很容易。(我想创建一个在创建时附加一些自定义特征的工作)

因此,首先查看github上的 Laravel存根。

接下来,选择想要的类类型的存根(我复制了作业排队的存根)并将其粘贴到可以在应用程序中访问的位置。我把我的放进去了,App\Console\Stubs因为这将使命令使用存根。

之后,使用创建您的工匠命令php artisan make:command commandName

在创建的命令内部使用此文件Illuminate\Console\GeneratorCommand。现在,使您的命令扩展该类,而不是Command; 该类是Laravel用于创建类的类,并且它Command自身进行了扩展。

在命令内部创建一些属性和方法,如下所示:

protected $name = 'make:custom-file'; The name of your command. This replaces $signature

protected $description = 'Command description.';

protected $type = 'Job'; Type of class to make

//location of your custom stub
protected function getStub()
{
    return  app_path().'/Console/Stubs/custom-job.stub';
}

//The root location the file should be written to
protected function getDefaultNamespace($rootNamespace)
{
    return $rootNamespace.'\Jobs';
}

//option flags if any see this for how it works
protected function getOptions()
{
    return [];
}
Run Code Online (Sandbox Code Playgroud)

该类的外观的完整示例如下:

<?php

namespace App\Console\Commands;

use Illuminate\Console\GeneratorCommand;

class CustomJob extends GeneratorCommand
{

    /**
    * The name and signature of the console command.
    *
    * @var string
    */
    protected $name = 'make:custom';

    /**
    * The console command description.
    *
    * @var string
    */
    protected $description = 'Create a custom job.';

    /**
    * The type of class being generated.
    *
    * @var string
    */
    protected $type = 'Job';

    /**
    * Get the stub file for the generator.
    *
    * @return string
    */
    protected function getStub()
    {
        return  app_path().'/Console/Stubs/custom-job.stub';
    }

    /**
    * Get the default namespace for the class.
    *
    * @param  string  $rootNamespace
    * @return string
    */
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace.'\Jobs';
    }

    /**
    * Get the console command options.
    *
    * @return array
    */
    protected function getOptions()
    {
        return [];
    }
}
Run Code Online (Sandbox Code Playgroud)

一旦运行了定制artisan命令,它将把定制存根写入您指定的位置。


pat*_*cus 12

Laravel使用.stub文件作为模板,并替换模板内的标记.

由于您提到了该make:console命令,以供参考,您可以查看以下文件:

  • vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs/console.stub
    (在github上)
    这是用于创建新控制台命令的模板.
  • vendor/laravel/framework/src/Illuminate/Foundation/Console/ConsoleMakeCommand.php
    (在github上)
    这是运行php artisan make:console命令时执行的代码.

如果你想看一下这样做的包,一个很好的例子就是杰拉里·韦尔在拉克瑞斯特的发电机包.