【问题标题】:ARGUMENTS and OPTIONS with Laravel Illuminate Console CommandLaravel Illuminate 控制台命令的参数和选项
【发布时间】:2017-10-19 12:52:58
【问题描述】:

很清楚如何在 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);
    }
}

【问题讨论】:

    标签: php laravel console


    【解决方案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);
        }
    }
    

    【讨论】:

      【解决方案2】:

      有一个完整的文档部分专门用于从头开始创建命令,并且有据可查。仔细看看。

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-08-08
        • 1970-01-01
        • 2017-03-17
        • 2019-10-23
        • 1970-01-01
        • 2022-06-14
        • 2011-04-06
        相关资源
        最近更新 更多