Laravel Defining Input Expectations

When writing console commands, it is common to gather input from the user through arguments or options. Laravel makes it very convenient to define the input you expect from the user using the signature property on your commands. The signature property allows you to define the name, arguments, and options for the command in a single, expressive, route-like syntax.

Arguments
All user supplied arguments and options are wrapped in curly braces. In the following example, the command defines one required argument: user:
なんじゃこりゃ。

protected $signature = 'email:send {user}';

You may also make arguments optional and define default values for arguments:

email:send {user?}

// Optional argument with default value...
email:send {user=foo}

Options
Options, like arguments, are another form of user input. Options are prefixed by two hyphens (–) when they are specified on the command line. There are two types of options: those that receive a value and those that don’t. Options that don’t receive a value serve as a boolean “switch”. Let’s take a look at an example of this type of option:
optionは–と書きます。

/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'email:send {user} {--queue}';

In this example, the –queue switch may be specified when calling the Artisan command. If the –queue switch is passed, the value of the option will be true. Otherwise, the value will be false:

php artisan email:send 1 –queue

Options With Values
Next, let’s take a look at an option that expects a value. If the user must specify a value for an option, suffix the option name with a = sign:

protected $signature = 'email:send {user} {--queue=}';

In this example, the user may pass a value for the option like so:

php artisan email:send 1 –queue=default
You may assign default values to options by specifying the default value after the option name. If no option value is passed by the user, the default value will be used:

email:send {user} {–queue=default}
なんじゃこりゃ、email:sendってメール送付?

Option Shortcuts
To assign a shortcut when defining an option, you may specify it before the option name and use a | delimiter to separate the shortcut from the full option name:
email:send {user} {–Q|queue}

Input Arrays
If you would like to define arguments or options to expect array inputs, you may use the * character. First, let’s take a look at an example that specifies an array argument:

email:send {user*}
When calling this method, the user arguments may be passed in order to the command line. For example, the following command will set the value of user to [‘foo’, ‘bar’]:

php artisan email:send foo bar
When defining an option that expects an array input, each option value passed to the command should be prefixed with the option name:

email:send {user} {–id=*}

php artisan email:send –id=1 –id=2
ワイルドカードとオプション。オプションの使い勝手が良い。

Input Descriptions
You may assign descriptions to input arguments and options by separating the parameter from the description using a colon. If you need a little extra room to define your command, feel free to spread the definition across multiple lines:

protected $signature = 'email:send
                        {user : The ID of the user}
                        {--queue= : Whether the job should be queued}';

コメントみたいだけど、使い勝手は良さそう。わざわざやらんか。

Retrieving Input
While your command is executing, you will obviously need to access the values for the arguments and options accepted by your command. To do so, you may use the argument and option methods:

public function handle()
{
    $userId = $this->argument('user');

    //
}

Retrievingは取得って意味。mysqlのfetchばっかり使っていたが、retrievingにも慣れないと。。

$arguments = $this->arguments();
optionもretrievigか。

// Retrieve a specific option...
$queueName = $this->option('queue');

// Retrieve all options...
$options = $this->options();

If the argument or option does not exist, null will be returned.

Prompting For Input
In addition to displaying output, you may also ask the user to provide input during the execution of your command. The ask method will prompt the user with the given question, accept their input, and then return the user’s input back to your command:

The secret method is similar to ask, but the user’s input will not be visible to them as they type in the console. This method is useful when asking for sensitive information such as a password:

$password = $this->secret(‘What is the password?’);
Asking For Confirmation
If you need to ask the user for a simple confirmation, you may use the confirm method. By default, this method will return false. However, if the user enters y or yes in response to the prompt, the method will return true.

Auto-Completion
The anticipate method can be used to provide auto-completion for possible choices. The user can still choose any answer, regardless of the auto-completion hints:

$name = $this->anticipate(‘What is your name?’, [‘Taylor’, ‘Dayle’]);
Multiple Choice Questions
If you need to give the user a predefined set of choices, you may use the choice method. You may set the array index of the default value to be returned if no option is chosen:
$name = $this->choice(‘What is your name?’, [‘Taylor’, ‘Dayle’], $defaultIndex);

Writing Output
To send output to the console, use the line, info, comment, question and error methods. Each of these methods will use appropriate ANSI colors for their purpose. For example, let’s display some general information to the user. Typically, the info method will display in the console as green text:
これは実践でやらんとわからんわ。

public function handle()
{
    $this->info('Display this on the screen');
}
$this->error('Something went wrong!');
$this->line('Display this on the screen');

Table Layouts
The table method makes it easy to correctly format multiple rows / columns of data. Just pass in the headers and rows to the method. The width and height will be dynamically calculated based on the given data:

$headers = ['Name', 'Email'];
$users = App\User::all(['name', 'email'])->toArray();
$this->table($headers, $users);

Progress Bars
For long running tasks, it could be helpful to show a progress indicator. Using the output object, we can start, advance and stop the Progress Bar. First, define the total number of steps the process will iterate through. Then, advance the Progress Bar after processing each item:
progress barsはjsかcssだろ。

$users = App\User::all();

$bar = $this->output->createProgressBar(count($users));

foreach ($users as $user) {
    $this->performTask($user);

    $bar->advance();
}

$bar->finish();

performTask($user);とprogressbarが上手くリンクせんな。

Registering Commands
Because of the load method call in your console kernel’s commands method, all commands within the app/Console/Commands directory will automatically be registered with Artisan. In fact, you are free to make additional calls to the load method to scan other directories for Artisan commands:

protected function commands()
{
$this->load(__DIR__.’/Commands’);
$this->load(__DIR__.’/MoreCommands’);

// …
}

Programmatically Executing Commands
Sometimes you may wish to execute an Artisan command outside of the CLI. For example, you may wish to fire an Artisan command from a route or controller. You may use the call method on the Artisan facade to accomplish this. The call method accepts either the command’s name or class as the first argument, and an array of command parameters as the second argument. The exit code will be returned:

Route::get('/foo', function () {
    $exitCode = Artisan::call('email:send', [
        'user' => 1, '--queue' => 'default'
    ]);

    //
});

Artisan::call(’email:send’ これはなんだ?controllerの中でartisanって書けるの?コマンドラインだけではないのか。。

Using the queue method on the Artisan facade, you may even queue Artisan commands so they are processed in the background by your queue workers. Before using this method, make sure you have configured your queue and are running a queue listener:
queuesをcallのところで使用している。

Route::get('/foo', function () {
    Artisan::queue('email:send', [
        'user' => 1, '--queue' => 'default'
    ]);

    //
});
Artisan::queue('email:send', [
    'user' => 1, '--queue' => 'default'
])->onConnection('redis')->onQueue('commands');