使用Laravel Illuminate控制台命令的参数和选项

时间:2017-05-19 11:45:45

标签: php laravel console

很清楚如何在Laravel中为CLI创建一个简单的命令,这也适用于创建参数,但我似乎无法找到有关如何为CLI创建选项的简单文档

我想这样做,以便用户可以在参数后添加选项。 例如:

php artisan cmd参数-a

php artisan cmd参数-a -c -x

如何在下面的课程中实现这样的结构?

更新了代码 确实有一些可能的解决方案。它实际上很容易退出。

class cmd extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cmd {argument} 
                           {--s : description}
                           {--x : description}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     * 
     * @return mixed
     */
    public function handle()
    {

       $var = $this->argument('argument');
       $options = $this->options();

       new Main($var,$options);
    }
}

2 个答案:

答案 0 :(得分:1)

对此有很多可行的解决方案,但我更喜欢添加可选参数,如果它们存在则使用?执行确定的操作,这意味着参数可以存在或不存在,加上*这意味着可以更棕褐色,像这样:

class cmd extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cmd {argument} {-extra*?}';


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     * 
     * @return mixed
     */
    public function handle()
    {

       $var = $this->argument('argument');
       if($this->argument('-extra')) {
         //do things if -extra argument exists, it will be an array with the extra arguments value...
       }

       new Main($var);
    }
}

答案 1 :(得分:0)

整个文档部分专门用于从头开始创建命令,并且已有详细记录。仔细看看。

https://laravel.com/docs/5.4/artisan

如果您需要从示例中学习,那么请查看所有laravel的内置控制台命令。

vendor/laravel/framework/src/Illuminate/Foundation/Console