Reputation: 881
It's pretty clear how to create a simple command for the CLI in Laravel and this goes also for creating arguments, but I can't seem to find a simple documentation on how to create options for the CLI.
I want to make it so that the user can add options after the argument. So for example:
php artisan cmd argument -a
php artisan cmd argument -a -c -x
How do I implement such a structure in the class below?
Updated code There are indeed a few possible solutions. It was actually quit easy.
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);
}
}
Upvotes: 1
Views: 12410
Reputation: 7013
There are a lot of posible solutions for this, but I prefer to add optional arguments and if they exist do determinate actions with the ?
that means argument can exist or not, plus *
this means can be more tan one, like this:
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);
}
}
Upvotes: 1
Reputation: 11906
There a whole doc section dedicated to creating commands from scratch and it's well documented. Look through it.
https://laravel.com/docs/5.4/artisan
If you need to learn from examples then have a look here into all the laravel's built in console commands.
vendor/laravel/framework/src/Illuminate/Foundation/Console
Upvotes: 0