[Laravel5.2 documentation] service-ArtisanConsole
1. Introduction
Artisan is the name of the command line interface provided by Laravel. It provides many useful commands during development. It is driven by the powerful SymfonyConsole component. To view all available Artisan commands, run the list command:
php artisan list
Each command can use the help command to display the command description, command parameters, and options. To view the help page, you only need to add help before the command:
php artisan help migrate
2. write commands
In addition to the commands provided by Artisan, you can also build your own commands. You can store custom Commands in the app/Console/Commands Directory. of course, you can choose the storage location as long as the command can be automatically loaded by composer. json.
To create a new command, you can use the Artisan command make: console:
php artisan make:console SendEmails
The above command will generate a class app/Console/Commands/SendEmails. php. when creating a command, the -- command option can be used to assign the terminal command name (used when the terminal calls the command ):
php artisan make:console SendEmails --command=emails:send
Command structure
After the command is generated, you must enter the signature and description attributes of the class. These two attributes are used when you call the list display command.
The handle method is called during command execution. you can put all command logic in this method. let's look at a command example first.
We can inject any dependencies into the constructor of the command controller. the Laravel service provider will automatically inject all dependency types in the constructor. It is a good practice to enhance code reusability, keep code light and delay it to the application service to complete the task:
Drip = $ drip;}/*** run the Console Command ** @ return mixed */public function handle () {$ this-> drip-> send (User :: find ($ this-> argument ('user ')));}}
3. command I/O3.1 define expected input
When writing console commands, user input is usually collected through Parameters and options. Laravel makes this operation easy: use the signature attribute in the command to define the user input we expect. The signature attribute allows you to define command names, parameters, and options through an elegant, routing-style syntax. All parameters and options provided by users are included in braces. the commands defined in the following example require users to enter the required parameter user:
/*** Console command name ** @ var string */protected $ signature = 'Email: send {user }';
You can also make this parameter optional and define the default optional parameter values:
// Option parameter... email: send {user ?} // Option parameter with default value... email: send {user = foo}
Option, like a parameter, is also a format of user input. The difference is that there are two hyphens (-) before the option. we can define the option as follows:
/*** Console command name ** @ var string */protected $ signature = 'Email: send {user} {-- queue }';
In this example, the -- queue switch is specified when the Artisan command is called. If the -- queue switch is passed, its value is true; otherwise, its value is false:
php artisan email:send 1 --queue
You can also specify the option value to be allocated by the user through =:
/*** Console command name ** @ var string */protected $ signature = 'Email: send {user} {-- queue = }';
In this example, you can pass the value in the following way:
php artisan email:send 1 --queue=default
You can also assign default values to options:
email:send {user} {--queue=default}
If you want to assign a short name to a command option, you can specify and use a separator before the option | separate the short name from the full option name:
email:send {user} {--Q|queue}
If you want to define parameters and options to specify the input array, you can use the character *:
email:send {user*}email:send {user} {--id=*}
Input description
You can use colons to separate parameters and descriptions to assign descriptions to input parameters and options:
/*** Console command name ** @ var string */protected $ signature = 'Email: send {user: The ID of the user} {-- queue =: whether the job shocould be queued }';
3.2 get input
When the command is executed, it is obvious that you need to access the parameter and option value obtained by the command. You can use the argument and option methods to achieve this:
To obtain the parameter value, use the argument method:
/*** Run the Console Command ** @ return mixed */public function handle () {$ userId = $ this-> argument ('user ');}
If you need to obtain all the parameter values in an array, use argument without parameters:
$arguments = $this->argument();
The option value is as simple as the parameter value. The option method is used. if you want to obtain all option values like argument, you can call the option method without parameters:
// Obtain the specified option... $ queueName = $ this-> option ('queue '); // Obtain all options... $ options = $ this-> option ();
If the parameter or option does not exist, null is returned.
3.3 input prompt
In addition to display output, you may need to provide input during command execution. The ask method prompts the user with a given question, receives the input, and returns the user input to the command:
/*** Run the Console Command ** @ return mixed */public function handle () {$ name = $ this-> ask ('What is your name? ');}
The secret method is similar to the ask method, but user input is invisible to users on the terminal. this method is useful when users are asked about sensitive information such as passwords:
$password = $this->secret('What is the password?');
Confirm with the user
If you want the user to confirm the information, you can use the confirm method. by default, this method returns false. if the user inputs y, this method returns true:
if ($this->confirm('Do you wish to continue? [y|N]')) { //}
Provide users with selection
The anticipate method can be used to automatically complete possible options. you can still choose the answer, regardless of the options:
$name = $this->anticipate('What is your name?', ['Taylor', 'Dayle']);
You can use the choice method if you want to give users a pre-defined choice. The user selects the index of the answer, but returns the value of the answer. If you have not selected any options, you can set the default value returned:
$name = $this->choice('What is your name?', ['Taylor', 'Dayle'], false);
3.4 write and output
To send the output to the console, use the line, info, comment, question, and error methods. each method uses the corresponding ANSI color for identification.
To display an information message to the user, use the info method. Normally, the terminal is displayed in green:
/*** Run the Console Command ** @ return mixed */public function handle () {$ this-> info ('display this on the screen ');}
To display an error message, use the error method. The error message text is usually red:
$this->error('Something went wrong!');
If you want to display native output, you can use the line method. the output characters do not contain color:
$this->line('Display this on the screen');
Table layout
The table method makes it easy to output data in multi-row/column format. you only need to pass the header and row to this method. the width and height are automatically calculated based on the given data:
$headers = ['Name', 'Email'];$users = App\User::all(['name', 'email'])->toArray();$this->table($headers, $users);
Progress Bar
It is useful to display the progress indicator for a task that requires a long time to run. with this output object, we can start, forward, and stop the progress bar. When starting the progress, you must define the number of steps and move each step forward with a progress bar:
$users = App\User::all();$this->output->progressStart(count($users));foreach ($users as $user) { $this->performTask($user); $this->output->progressAdvance();}$this->output->progressFinish();
For more information, see the Symfony progress bar component documentation.
4. Register commands
After writing the command, you must register it with Artisan to use it. this can be done in the app/Console/Kernel. php file.
In this file, you will see a command list in the commands attribute. to register your command, you just need to add it to the list. When Artisan is started, the commands listed in this attribute will be registered to Artisan by the service container resolution:
protected $commands = [ 'App\Console\Commands\SendEmails'];
5. call commands through code
Sometimes you may want to execute the Artisan command outside the CLI. for example, you may want to trigger the Artisan command in the route or controller. you can use the call method on the Artisan facade to complete this. The name of the command received by the call method is the first parameter, and the array of command parameters is the second parameter. the exit code is returned:
Route::get('/foo', function () { $exitCode = Artisan::call('email:send', [ 'user' => 1, '--queue' => 'default' ]);});
Using the queue method on Artisan, you can even put Artisan commands in the queue so that they can be processed by the backend queue workers:
Route::get('/foo', function () { Artisan::queue('email:send', [ 'user' => 1, '--queue' => 'default' ]);});
If you need to specify the option value that does not receive a string, such as the -- force identifier on the migrate: refresh command, you can pass a Boolean value of true or false:
$exitCode = Artisan::call('migrate:refresh', [ '--force' => true,]);
Call other commands
Sometimes you want to call other commands from an existing Artisan command. You can achieve this by using the call method. Command parameters in the array form and command names received by the call method:
/*** Run the Console Command ** @ return mixed */public function handle () {$ this-> call ('email: send', ['user' => 1, '-- queue' => 'default']);}
If you want to call other console commands and stop all their output, you can use the callSilent method. The callSilent method and call method are used in the same way:
$this->callSilent('email:send', [ 'user' => 1, '--queue' => 'default']);